2012-12-05 92 views
1

喜算colums和組我有這樣一個的Oracle SQL日期

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

什麼是你的Oracle版本? – Mat

+0

嗨,oracle數據庫11g – rjavy

+0

然後考慮爲此使用一個數據透視表(http://www.oracle-base.com/articles/11g/pivot-and-unpivot-operators-11gr1.php)。 – Mat

回答

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中,你可以使用現代化的樞紐條款:)

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

+0

優秀...!剛剛好。如果我想要一個額外的列,這三個來源的總和呢?非常感謝 – rjavy

+0

@rjavy,那就是'sum(1)'或'count(*)' –

+0

你是對的。謝謝你的幫助 – rjavy