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.
| 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 thisselect 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 Commentfrom [User]uinner join UserLog ul on u.UserId=ul.UserId |
 |
|
|
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 thisselect 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 Commentfrom [User]uinner join UserLog ul on u.UserId=ul.UserIdgroup by Nick
Karthik |
 |
|
|
ayamas
Aged Yak Warrior
552 Posts |
Posted - 2009-04-09 : 07:52:58
|
| Oops missed that one.Thanks for the catch. |
 |
|
|
madhivanan
Premature Yak Congratulator
22864 Posts |
Posted - 2009-04-09 : 08:32:01
|
| Other method isselect 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 Commentfrom [User]uinner join UserLog ul on u.UserId=ul.UserIdgroup by NickMadhivananFailing to plan is Planning to fail |
 |
|
|
|
|
|
|
|