| Author |
Topic |
|
prajeeshkk
Starting Member
3 Posts |
Posted - 2009-12-24 : 02:10:33
|
| Hi, suppose below is my table.User_id Depth childcount3 0 13 1 104 0 15 0 15 1 265 2 615 3 245 4 135 5 115 6 75 7 35 8 16 0 17 0 1I want to select user_ids who is having minimum 5 childs in depths 1 to 5. here the user_id 5 will come .Please help me to write down a query to achieve this. |
|
|
bklr
Master Smack Fu Yak Hacker
1693 Posts |
Posted - 2009-12-24 : 02:15:09
|
| [code]SELECT user_id FROM (select 3 as User_id, 0 Depth, 1 childcount union all select3, 1, 10 union all select4, 0, 1 union all select5, 0, 1 union all select5, 1, 26 union all select5, 2, 61 union all select5, 3, 24 union all select5, 4, 13 union all select5, 5, 11 union all select5, 6, 7 union all select5, 7, 3 union all select5, 8, 1 union all select6, 0, 1 union all select7, 0, 1)s WHERE depth BETWEEN 1 and 5GROUP BY user_idHAVING count(user_id) >= 5[/code] |
 |
|
|
Sachin.Nand
2937 Posts |
Posted - 2009-12-24 : 02:46:29
|
| I think there is no need for the where clause.PBUH |
 |
|
|
bklr
Master Smack Fu Yak Hacker
1693 Posts |
Posted - 2009-12-24 : 03:01:10
|
quote: Originally posted by Idera I think there is no need for the where clause.PBUH
for given data no need of where clause but in the question he mention the depth between 1 to 5 so that i kept the where clause...... |
 |
|
|
Sachin.Nand
2937 Posts |
Posted - 2009-12-24 : 04:20:25
|
| Yes thats right.Missed on that one.PBUH |
 |
|
|
ms65g
Constraint Violating Yak Guru
497 Posts |
Posted - 2009-12-26 : 07:22:23
|
Your question is not completely in spec. I guess you're looking for Relational Division.SET NOCOUNT ONDECLARE @your_table TABLE(User_id int, Depth int, childcount int) INSERT INTO @your_tableselect 3 as User_id, 0 Depth, 1 childcount union all select3, 1, 10 union all select4, 0, 1 union all select5, 0, 1 union all select5, 1, 26 union all select5, 2, 61 union all select5, 3, 24 union all select5, 4, 13 union all select5, 5, 11 union all select5, 6, 7 union all select5, 7, 3 union all select5, 8, 1 union all select6, 0, 1 union all select7, 0, 1 SELECT user_id FROM @your_table GROUP BY user_idHAVING SUM(CASE WHEN depth IN (1,2,3,4,5) THEN 1 ELSE 0 END)>=5--ORSELECT user_id FROM @your_table GROUP BY user_idHAVING MAX(CASE WHEN depth = 1 THEN 1 ELSE 0 END) = 1 AND MAX(CASE WHEN depth = 2 THEN 1 ELSE 0 END) = 1 AND MAX(CASE WHEN depth = 3 THEN 1 ELSE 0 END) = 1 AND MAX(CASE WHEN depth = 4 THEN 1 ELSE 0 END) = 1 AND MAX(CASE WHEN depth = 5 THEN 1 ELSE 0 END) = 1 |
 |
|
|
|
|
|