原始表如下格式:
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 @[email protected]+',[callcount'+class+']=sum(case when class='''+class+''' then callcount else 0 end)'
from t
group by class
set @[email protected]+' 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
新闻热点
疑难解答