选择特定的行
查询结果如下:
id1 id2 r num
21 3 -1 5
21 3 0 4
1 4 -1 12
1 4 0 7
1 4 1 9
2 2 -1 1
2 2 1 10
1 3 -1 21
1 3 0 12
1 3 1 3
.. .. .. ..
有id1/id2两个关键字,r最多有-1/0/1三种选择,num是任意整数
希望选择只有两个R的那些记录,以及有3个R,同时NUM <=3的记录
比如
最终希望得到下面的结果
-1 0 1
21 3 5 4
2 2 1 10
1 3 21 12 3
------解决方案--------------------/*------------------------
create table tb(id1 int, id2 int, r int, num int)
insert tb select 21,3,-1,5
union all select 21,3,0,4
union all select 1, 4,-1,12
union all select 1, 4,0,7
union all select 1, 4,1,9
union all select 2, 2,-1,1
union all select 2, 2,1,10
union all select 1, 3,-1,21
union all select 1, 3,0,12
union all select 1, 3,1,3
select id1,id2, num1=case num_b1 when 0 then ' ' else rtrim(num_b1) end
, num2=case num_0 when 0 then ' ' else rtrim(num_0) end
, num2=case num_1 when 0 then ' ' else rtrim(num_1) end
from(
select id1, id2,
num_b1=sum(case r when -1 then num else 0 end),
num_0=sum(case r when 0 then num else 0 end),
num_1=sum(case r when 1 then num else 0 end)
from tb
group by id1, id2
having count(r)=2 or (count(r)=3 and min(num) <=3)
) T
drop table tb
------------------------*/
(10 row(s) affected)
id1 id2 num1 num2 num2
----------- ----------- ------------ ------------ ------------
2 2 1 10
1 3 21 12 3
21 3 5 4
(3 row(s) affected)