[英]Oracle SQL count colums and group by date
Hi I have a table like this one 嗨,我有一张这样的桌子
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
How can I have the count by source and by date as follows: 我如何按来源和日期进行计数,如下所示:
c_date
source a source b source c c_date
来源a来源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..
The closest I have got is something like 我最近的是这样的
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
but it repeats the total count for each row I cannot find how to relate the count colums with the date. 但是它重复了每一行的总计数,我找不到如何将计数列与日期联系起来。
Thanks a lot for your help 非常感谢你的帮助
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
update as long as you use 11g, you can use modern pivot clause :) 只要您使用11g进行更新 ,就可以使用现代数据透视子句:)
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;
http://sqlfiddle.com/#!4/d0269/16 http://sqlfiddle.com/#!4/d0269/16
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.