>-- universes >id campaign_id user_id query_name >----------- ----------- ----------- ------------------ >16 134 2 Another Test >17 134 2 My Test >18 134 2 Some Universe >22 134 2 Kevin's Universe > >(4 row(s) affected) > >-- universe_xref_voters >id universe_id voter_id >----------- ----------- ----------- >11 16 1945386 >12 16 1976110 >13 16 1954564 > >(3 row(s) affected) >>
>SELECT u.id, u.campaign_id, u.user_id, u.query_name, u.query_desc, v.voter_id > FROM universes u > JOIN universe_xref_voters v ON v.universe_id = u.id > WHERE u.Campaign_Id = 134 > ORDER BY u.Query_Name >>
>voter_id id campaign_id user_id query_name >----------- ----------- ----------- ----------- ------------ >1945386 16 134 2 Another Test >1976110 16 134 2 Another Test >1954564 16 134 2 Another Test > >(3 row(s) affected) > >>
DECLARE @Universes TABLE (id int, campaign_id int, userid int, query_name varchar(200)) INSERT INTO @Universes VALUES (16, 134, 2, 'Another Test') INSERT INTO @Universes VALUES (17, 134, 2, 'My Test') INSERT INTO @Universes VALUES (18, 134, 2, 'Some Universe') INSERT INTO @Universes VALUES (22, 134, 2, 'Kevin''s Universe') DECLARE @Universe_xref_voters TABLE (id int, universe_id int, voter_id int) INSERT INTO @Universe_xref_voters VALUES (11, 16, 1945386) INSERT INTO @Universe_xref_voters VALUES (12, 16, 1976110) INSERT INTO @Universe_xref_voters VALUES (13, 16, 1954564) SELECT u.id, u.campaign_id, u.userid, u.query_name, -- u.query_desc, v.voter_id, ISNULL(Total.Cnt, 0) AS TotalVoters FROM @Universes u LEFT JOIN @universe_xref_voters v ON v.universe_id = u.id LEFT JOIN (SELECT universe_id, COUNT(*) AS Cnt FROM @universe_xref_voters GROUP BY universe_id) Total ON Total.universe_id = u.id WHERE u.Campaign_Id = 134 ORDER BY u.Query_Name?