If you are using Oracle 11g, then you can use the PIVOT
function:
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;
See SQL Fiddle with Demo
If you are not using Oracle11g, then you can use an aggregate function with a CASE
statement:
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
See SQL Fiddle with Demo
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…