Oracle sql在单列中计算不同值的实例

时间:2012-11-05 18:31:27

标签: oracle pivot

我有一个状态列表。我想要一个Oracle sql查询,它会在一行中列出每个状态中的行数。 例如,如果我的表是

Table A
Id       Status  Fkey
1         20      500
2         20      500  
3         30      501
4         40      501
5         30      502

输出应为

Fkey     Count_status20     Count_status30    Count_status40
500        2                      0                 0
501        0                      1                 1

稍微扭曲

Table B 
FKey TKey 
500   1001 
501   1001
502   1002 

现在输出应

TKey Count_status20     Count_status30    Count_status40 
1001     2                     1                    1 
1002     0                     1                    0

2 个答案:

答案 0 :(得分:13)

如果您使用的是Oracle 11g,则可以使用PIVOT功能:

select *
from
(
  select tkey, status, 
    status as col
  from tableB b
  left join tableA a
    on a.fkey = b.fkey
) src
pivot
(
  count(status)
  for col in ('20' as Count_Status20, 
              '30' as Count_Status30,
              '40' as Count_Status40)
) piv;

请参阅SQL Fiddle with Demo

如果您没有使用Oracle11g,那么您可以使用带有CASE语句的聚合函数:

select tkey, 
  count(case when status = 20 then 1 else null end) as Count_Status20,
  count(case when status = 30 then 1 else null end) as Count_Status30,
  count(case when status = 40 then 1 else null end) as Count_Status40
from tableB b
left join tableA a
  on b.fkey = a.fkey
group by tkey

请参阅SQL Fiddle with Demo

答案 1 :(得分:3)

select fkey,
       sum(case when status = 20 then 1 else 0 end) as count_status20,
       sum(case when status = 30 then 1 else 0 end) as count_status30,
       sum(case when status = 40 then 1 else 0 end) as count_status40,
from your_table
group by fkey