1

嗨,我有一张像这样的桌子

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来源 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..

我得到的最接近的是

 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 

但它重复每一行的总计数我找不到如何将计数列与日期联系起来。

非常感谢你的帮助

4

1 回答 1

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;

http://sqlfiddle.com/#!4/d0269/16

于 2012-12-05T17:55:47.417 回答