首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

请问一个sql统计的有关问题

2013-06-26 
请教一个sql统计的问题 以上是建立测试数据,大致需求是:有一张表记录了公司各个部门的快递使用费用,现在要

请教一个sql统计的问题


 以上是建立测试数据,大致需求是:有一张表记录了公司各个部门的快递使用费用,现在要统计每个部门的快递费用使用情况,需要得出结果如下的一张表,
请教一下各位大神这个sql语句应该怎么写
请问一个sql统计的有关问题
SQL
[解决办法]

select dep,depid,
sum(case when company ='DHL' then cost else 0 end)DHL,
sum(case when company ='EMS' then cost else 0 end)EMS,
sum(case when company ='TNT' then cost else 0 end)TNT,
sum(case when company ='SF' then cost else 0 end)SF,
sum(cost)cost
FROM #test group by dep,depid

[解决办法]
DECLARE @s NVARCHAR(4000)
SET @s = ''
SELECT  @s = @s + ',' + QUOTENAME([company]) + '=max(case when [company]='
        + QUOTENAME([company], '''') + ' then [cost] else 0 end)'
FROM    #test
GROUP BY [company]
EXEC('select dep,depid'+@s+' from #test group by dep,depid')
 

热点排行