日期:2014-05-18 浏览次数:20507 次
--> 测试数据:[test]
if object_id('[test]') is not null drop table [test]
create table [test]([部门] varchar(8),[收入] varchar(5),[人数] int)
insert [test]
select '生产一部','0-1万',10 union all
select '生产一部','1-2万',5 union all
select '生产一部','2-3万',2 union all
select '生产二部','0-1万',8 union all
select '生产二部','1-2万',5 union all
select '生产二部','2-3万',2 union all
select '生产三部','0-1万',2 union all
select '生产三部','2-3万',3 union all
select '生产四部','3-4万',4
declare @str varchar(8000)
set @str=''
select
@str=@str+',['+[收入]+']=sum(case when [收入]='+QUOTENAME([收入],'''')+
' then [人数] else 0 end)' from test group by [收入]
exec('select [部门]'+@str+' from test group by [部门]')
/*
部门 0-1万 1-2万 2-3万 3-4万
生产二部 8 5 2 0
生产三部 2 0 3 0
生产四部 0 0 0 4
生产一部 10 5 2 0
*/
------解决方案--------------------
select 部门, max(case 收入 when '0-1万' then 人数 else 0 end) as '0-1万', max(case 收入 when '1-2万' then 人数 else 0 end) as '1-2万', .. from tb group by 部门
------解决方案--------------------
你直接写个存储过程,然后把这个语句放到里面,你按照sql查询的形式给遍历出来就好了
我的异常网推荐解决方案:软件开发者薪资,http://www.aiyiweb.com/other/1391128.html