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 |
zoe2003
Starting Member
17 Posts |
Posted - 2013-06-10 : 09:12:40
|
Hi everyone,I need your help with the below logic:I have this table:user milestone1 01 9992 02 23 13 23 9994 9995 NULLIt represents users and the milestones they've reached.I need an sql query that will count distinct :1. The users who've reached milestones 0 and 999.2. Reached 999 but not 0.3. Reached 0 but not 999.4. Haven't reached none of them.This is the expected result :user type count distinct both 1no 0 2no 999 1missing both 1Thanks,Z |
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2013-06-10 : 10:09:25
|
[code]SELECT CASE WHEN MinVal <> MaxVal THEN 'Both' WHEN MinVal = 0 THEN 'Reached 0 Not 999' WHEN MinVal = 999 THEN 'Reached 999 Not 0' WHEN MinVal IS NULL THEN 'Reached None' END AS Cat,COUNT(*) AS CntFROM(SELECT user,MIN(CASE WHEN milestone IN (0,999) THEN milestone END) AS MinVal,MAX(CASE WHEN milestone IN (0,999) THEN milestone END) AS MaxValFROM TableGROUP BY user)tGROUP BY CASE WHEN MinVal <> MaxVal THEN 'Both' WHEN MinVal = 0 THEN 'Reached 0 Not 999' WHEN MinVal = 999 THEN 'Reached 999 Not 0' WHEN MinVal IS NULL THEN 'Reached None' END[/code]------------------------------------------------------------------------------------------------------SQL Server MVPhttp://visakhm.blogspot.com/https://www.facebook.com/VmBlogs |
 |
|
Hommer
Aged Yak Warrior
808 Posts |
Posted - 2013-06-10 : 10:41:03
|
And if you run into "Each GROUP BY expression must contain at least one column that is not an outer reference", just add [] to column name user inside the t. |
 |
|
zoe2003
Starting Member
17 Posts |
Posted - 2013-06-10 : 11:08:49
|
Thanks. |
 |
|
|
|
|