Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 Need some input on this Query

Author  Topic 

olaj
Starting Member

1 Post

Posted - 2009-04-09 : 07:37:12
Sorry for the bad title. I could not figure out any good one.

Anyway. I have this query and it's not very elegant and effective. Is there any better way to do this? Im sure there is but my brain doesn't work very good right now.

SELECT Nick,
Added = (SELECT Count(*) FROM UserLog WHERE UserId = u.UserId AND Activity = 1),
Liked = (SELECT Count(*) FROM UserLog WHERE UserId = u.UserId AND Activity = 0),
Comment = (SELECT Count(*) FROM UserLog WHERE UserId = u.UserId AND Activity = 2)
FROM [User] u

ayamas
Aged Yak Warrior

552 Posts

Posted - 2009-04-09 : 07:47:11
Try this

select Nick,
count(case when ul.Activity=1 then u.UserId end)as Added,
count(case when ul.Activity=0 then u.UserId end)as Liked,
count(case when ul.Activity=2 then u.UserId end)as Comment
from [User]u
inner join UserLog ul on u.UserId=ul.UserId
Go to Top of Page

karthik_padbanaban
Constraint Violating Yak Guru

263 Posts

Posted - 2009-04-09 : 07:52:07
I think you missed group by
quote:
Originally posted by ayamas

Try this

select Nick,
count(case when ul.Activity=1 then u.UserId end)as Added,
count(case when ul.Activity=0 then u.UserId end)as Liked,
count(case when ul.Activity=2 then u.UserId end)as Comment
from [User]u
inner join UserLog ul on u.UserId=ul.UserId
group by Nick



Karthik
Go to Top of Page

ayamas
Aged Yak Warrior

552 Posts

Posted - 2009-04-09 : 07:52:58
Oops missed that one.Thanks for the catch.
Go to Top of Page

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2009-04-09 : 08:32:01

Other method is


select Nick,
sum(case when ul.Activity=1 then 1 else 0 end)as Added,
sum(case when ul.Activity=0 then 1 else 0 end)as Liked,
sum(case when ul.Activity=2 then 1 else 0 end)as Comment
from [User]u
inner join UserLog ul on u.UserId=ul.UserId
group by Nick


Madhivanan

Failing to plan is Planning to fail
Go to Top of Page
   

- Advertisement -