日期:2014-05-17  浏览次数:20909 次

SQL分组统计求助。。谢谢
有数据 如下
ID1 ID2 STS COUNT
0001 01 S 4
0001 01 F 8000
0001 02 S 211
0001 02 F 2
0001 03 S 22
0001 03 F 2
0001 04 S 85
0001 05 F 2
0001 05 S 15

我想根据 ID1 ID2 分组
分别取STS 状态 为S F两种的 COUNT值,有的 同 ID1 ID2下,只有S,或只有F,那么缺失的count值为0



同一个ID2字段下面,只有两种STS的可能 S 或者 F 
或者 只有 一种,那么就说明 另一种为0
比如 第七条,只有S的记录,没有F,那么就说明F为0




我想得到结果

ID1 ID2 S COUNTS F COUNTF
0001 01 S 4 F 8000
0001 02 S 211 F 2
0001 03 S 22 F 2
0001 04 S 85 F 0
0001 05 S 15 F 2  


求SQL....

ORACLE


------解决方案--------------------
SQL code

--sql:
with t as
(
select 1 a,'01' b,'S' c, 4 d from dual
union all
select 1,'01','F', 8000 from dual
union all
select 1,'02','S', 211 from dual
union all
select 1,'02','F', 2 from dual
union all
select 1,'03','S', 22 from dual
union all
select 1,'03','F', 2 from dual
union all
select 1,'04','S', 85 from dual
union all
select 1,'05','F', 2 from dual
union all
select 1,'05','S', 15 from dual
)
select a,b,'S' c,sum(case when c='S' then d else 0 end) S
         ,'F' d, sum(case when c='F' then d else 0 end) F
         from t
         group by a,b
--result:
1    01    S    4    F    8000
1    02    S    211    F    2
1    03    S    22    F    2
1    04    S    85    F    0
1    05    S    15    F    2