首页 > 开发 > 综合 > 正文

经常用到的交叉表问题,一般用动态SQL能生成动态列!

2024-07-21 02:22:45
字体:
来源:转载
供稿:网友

原始表如下格式:
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


  • 本文来源于网页设计爱好者web开发社区http://www.html.org.cn收集整理,欢迎访问。
  • 发表评论 共有条评论
    用户名: 密码:
    验证码: 匿名发表