动态行转列

----------------------------------------------------------------
--
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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值