嗨,我有一张像这样的桌子
C_DATE SOURCE
11/21/2012 A
11/22/2012 A
11/22/2012 A
11/22/2012 A
11/23/2012 A
11/23/2012 A
11/25/2012 A
11/26/2012 A
11/26/2012 B
11/26/2012 B
11/26/2012 B
11/21/2012 B
11/22/2012 B
11/22/2012 B
11/23/2012 B
11/23/2012 C
11/24/2012 C
11/24/2012 C
11/24/2012 C
11/24/2012 C
11/25/2012 C
我如何按来源和日期计算如下:
c_date
来源b来源c
11/21/2012 1 4 0
11/22/2012 1 1 1
11/23/2012 0 0 1
11/24/2012 and so on..
我最接近的是
select trunc(c_date) XDATE,
(select count(**) from TABLE where source='A') A,
(select count(**) from TABLE where source='B') B,
(select count(*) from TABLE where source='C') C
from TABLE
group by trunc(C_DATE)
order by trunc(C_DATE) asc
但它会重复每行的总计数,我找不到如何将计数列与日期联系起来。
非常感谢你的帮助
答案 0 :(得分:1)
select trunc(c_date) XDATE,
sum(case source when 'A' then 1 else 0 end) cnt_a,
sum(case source when 'B' then 1 else 0 end) cnt_b,
sum(case source when 'C' then 1 else 0 end) cnt_c,
from TABLE
group by trunc(C_DATE)
order by trunc(C_DATE) asc
更新只要您使用11g,就可以使用现代的pivot子句:)
select xdate, a, b, c
from
(select trunc(c_date) XDATE, source, count(*)
from tab
group by trunc(c_date), source )
pivot
( count(*) for source in ('A' a, 'B' b, 'C' c) )
order by 1;