Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
What's Wrong With This????
Message
General information
Forum:
Microsoft SQL Server
Category:
SQL syntax
Miscellaneous
Thread ID:
01520346
Message ID:
01520355
Views:
45
>The Data:
>
>
>-- 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)
>
>
>and my query
>
>
>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
>
>
>and the results
>
>
>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)
>
>
>
>Notice that I'm getting the universes tabel repeated 3 times. I should be getting back all 4 universe roes with a voter Id added on.
>
>My ultimate goal is to get a result set of universes with a count of voters assigned to each, but I can't get past this.
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
?
Against Stupidity the Gods themselves Contend in Vain - Johann Christoph Friedrich von Schiller
The only thing normal about database guys is their tables.
Previous
Reply
Map
View

Click here to load this message in the networking platform