經常用到的交叉表問題,一般用動態SQL能產生動態列!

來源:互聯網
上載者:User
動態|問題

原始表如下格式:
Class     CallDate    CallCount
1     2005-8-8    40
1     2005-8-7    6
2     2005-8-8    77
3     2005-8-9    33
3     2005-8-8    9
3     2005-8-7    21

根據Class的值,按日期分別統計出CallCount1,CallCount2,CallCount3。
當該日期無記錄時值為0
要求合并成如下格式:
CallDate  CallCount1  CallCount2  CallCount3
2005-8-9  0       0       33
2005-8-8  40      77      9
2005-8-7  6       0       21

--建立測試環境
Create table  T  (Class varchar(2),CallDate datetime, CallCount int)
insert into T select '1','2005-8-8',40
union all select '1','2005-8-7',6
union all select '2','2005-8-8',77
union all select '3','2005-8-9',33
union all select '3','2005-8-8',9
union all select '3','2005-8-7',21
--動態SQL
declare @s varchar(8000)
set @s='select CallDate '
select @s=@s+',[CallCount'+Class+']=sum(case when Class='''+Class+''' then CallCount else 0 end)'
from T
group by Class
set @s=@s+' from T group by CallDate order by CallDate desc '
exec(@s)

--結果

CallDate                                               CallCount1  CallCount2  CallCount3 
------------------------------------------------------ ----------- ----------- -----------
2005-08-09 00:00:00.000                                0           0           33
2005-08-08 00:00:00.000                                40          77          9
2005-08-07 00:00:00.000                                6           0           21

--刪除測試環境

drop table T




相關文章

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。