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 |
|
SamC
White Water Yakist
3467 Posts |
Posted - 2003-04-21 : 14:20:29
|
| CREATE TABLE MyTable (UserID INT ,Bonus INT)'Bonus' has values of 1, 2 or 3I need a query that will count the number of UserIDs that have only one distinct bonus value, 2 distinct bonus values and 3 etc.SELECT count(distinct bonus)FROM MyTableGroup By UserIDHaving count(distinct bonus) = 1Gives a recordset of rows with UserIDs with only 1 distinct bonus. But this seems painful to go from here to count the rowsselect count(*)from (SELECT count(distinct bonus)FROM MyTableGroup By UserIDHaving count(distinct bonus) = 1)Is there a better way to derive the count of users with 1 distinct bonus?Sam |
|
|
nr
SQLTeam MVY
12543 Posts |
Posted - 2003-04-21 : 16:02:49
|
| Don't think this is easierselect count(distinct UserID)from MyTable t1where not exists (select * from MyTable t2 where t1.UserID = t2.UserID and t1.bonus <> t2.bonus)Your query would look netter withselect UserID ==========================================Cursors are useful if you don't know sql.DTS can be used in a similar way.Beer is not cold and it isn't fizzy. |
 |
|
|
r937
Posting Yak Master
112 Posts |
Posted - 2003-04-21 : 17:43:33
|
select sub.bonuses, count(*) as users from ( select count(distinct bonus) as bonuses from MyTable group by userid ) as subgroup by sub.bonuses not tested rudyhttp://r937.com/ |
 |
|
|
SamC
White Water Yakist
3467 Posts |
Posted - 2003-04-21 : 19:02:32
|
| Thanks Rudy,Sam |
 |
|
|
|
|
|