日期:2014-05-18 浏览次数:20804 次
我的表是这样的:
create table tableA
(工资项目 varchar(20), 简写 varchar(20), 金额 int,月分 varchar(10)
)
insert into tableA values('房补', 'fb', 100, '201101')
insert into tableA values('保险', 'bx', 200, '201101')
insert into tableA values('房补', 'fb', 100, '201102')
insert into tableA values('保险', 'bx', 200, '201102')
declare @sql varchar(max)
set @sql='select 月分'
select @sql=@sql+',sum(case 工资项目 when '''+工资项目+''' then 金额 end) as ['+工资项目+']'
from(select distinct 工资项目 from tableA)a
SET @SQL=@SQL+' FROM TABLEA GROUP BY 月分'
print @sql
exec (@sql)
------解决方案--------------------
----------------------------
-- Author :fredrickhu(小F,向高手学习)
-- Date :2012-05-24 15:12:10
-- Version:
-- Microsoft SQL Server 2008 R2 (RTM) - 10.50.1617.0 (Intel X86)
-- Apr 22 2011 11:57:00
-- Copyright (c) Microsoft Corporation
-- Enterprise Edition on Windows NT 6.1 <X64> (Build 7600: ) (WOW64)
--
----------------------------
--> 测试数据:[tb]
if object_id('[tb]') is not null drop table [tb]
go
create table [tb]([工资项目] varchar(4),[简写] varchar(2),[金额] int,[月分] int)
insert [tb]
select '房补','fb',100,201101 union all
select '保险','bx',200,201101 union all
select '房补','fb',100,201102 union all
select '保险','bx',200,201102
--------------开始查询--------------------------
declare @sql varchar(8000)
set @sql = 'select 月分 '
select @sql = @sql + ' , max(case 工资项目 when ''' + 工资项目 + ''' then 金额 else 0 end) [' + 工资项目 + ']'
from (select distinct 工资项目 from tb) as a
set @sql = @sql + ' from tb group by 月分'
exec(@sql)
----------------结果----------------------------
/* 月分 保险 房补
----------- ----------- -----------
201101 200 100
201102 200 100
(2 行受影响)
*/
------解决方案--------------------
--> 测试数据:[test]
if object_id('[test]') is not null drop table [test]
create table [test]([工资项目] varchar(4),[简写] varchar(2),[金额] int,[月分] int)
insert [test]
select '房补','fb',100,201101 union all
select '保险','bx',200,201101 union all
select '房补','fb',100,201102 union all
select '保险','bx',200,201102
declare @str varchar(2000)
set @str=''
select @str=@str+','+[工资项目]+'=max(case when [工资项目]='
+QUOTENAME([工资项目],'''')+' then [金额] else 0 end)'
from [test] group by [工资项目]
exec('select [月分]'+@str+' from test group by [月分]')
/*
月分 保险 房补
201101 200 100
201102 200 100
*/
--动态的吧,假如你的项目太多了,还需要打那么多字
我的异常网推荐解决方案:软件开发者薪资,http://www.aiyiweb.com/other/1391128.html