----------------------------------------------------------------
-- Author :fredrickhu(小F,向高手学习)
-- Date :2010-01-16 17:11:17
-- Version:
-- Microsoft SQL Server 2005 - 9.00.4035.00 (Intel X86)
-- Nov 24 2008 13:01:59
-- Copyright (c) 1988-2005 Microsoft Corporation
-- Developer Edition on Windows NT 5.1 (Build 2600: Service Pack 3)
--
----------------------------------------------------------------
--> 测试数据:[tb]
if object_id('[tb]') is not null drop table [tb]
go
create table [tb]([employ_id] int,[year_text] int,[month_text] int,[days] varchar(3),[money] int)
insert [tb]
select 1,2010,1,'5#',10 union all
select 1,2010,1,'6#',10 union all
select 1,2010,1,'7#',10 union all
select 1,2010,1,'8#',10 union all
select 1,2010,1,'9#',10 union all
select 1,2010,1,'10#',10 union all
select 2,2010,1,'5#',10 union all
select 2,2010,1,'6#',10 union all
select 3,2010,1,'7#',10 union all
select 4,2010,1,'8#',10 union all
select 5,2010,1,'9#',10 union all
select 2,2010,1,'10#',10
--------------开始查询--------------------------
---动态
declare @sql varchar(8000)
set @sql = 'select employ_id '
select @sql = @sql + ' , sum(case days when ''' + days + ''' then money else 0 end) [' + days + ']'
from (select distinct days from tb) as a
set @sql = @sql + ' from tb group by employ_id'
exec(@sql)
--静态
select
employ_id ,
sum(case days when '10#' then money else 0 end) [10#] ,
sum(case days when '5#' then money else 0 end) [5#] ,
sum(case days when '6#' then money else 0 end) [6#] ,
sum(case days when '7#' then money else 0 end) [7#] ,
sum(case days when '8#' then money else 0 end) [8#] ,
sum(case days when '9#' then money else 0 end) [9#]
from
tb
group by
employ_id
----------------结果----------------------------
/* employ_id 10# 5# 6# 7# 8# 9#
----------- ----------- ----------- ----------- ----------- ----------- -----------
1 10 10 10 10 10 10
2 10 10 10 0 0 0
3 0 0 0 10 0 0
4 0 0 0 0 10 0
5 0 0 0 0 0 10
(5 行受影响)
*/
http://topic.csdn.net/u/20100116/17/f1579e90-1044-4243-b8ca-c8585e1028da.html