Oracle
 sql >> Base de Dados >  >> RDS >> Oracle

Oracle sql para contar instâncias de valores diferentes em uma única coluna


Se você estiver usando o Oracle 11g, poderá usar o PIVOT função:
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;

Veja SQL Fiddle com demonstração

Se você não estiver usando Oracle11g, poderá usar uma função agregada com um CASE demonstração:
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

Veja SQL Fiddle com demonstração