3

ステータス列のあるテーブルがあります。各ステータスの行数を1行だけリストするOracleSQLクエリが必要です。たとえば、私のテーブルが

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
4

2 に答える 2

14

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 FiddlewithDemoを参照してください

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 FiddlewithDemoを参照してください

于 2012-11-05T18:37:54.607 に答える
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
于 2012-11-05T18:34:16.417 に答える