如何实现这样的横表变纵表

bcsky 2006-01-13 04:46:58
数据如下:
--employeeid 工号
--jiab 加班天数
--appmonth 加班月份
--depart 部门名称
-------------------------------
employeeid,jiab,appmonth,depart
1 2 10 a
1 1 11 b
1 2 12 c
2 1 10 a
2 1 11 b
2 1 12 c
要求把数据展示成如下:
employeeid,10月部门,10月加班天数,11月部门,11月加班天数,12月部门,12月加班天数
1 a 2 b 1 c 2
2 a 1 b 1 c 1
请大家帮忙

...全文
332 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
dagecc 2006-01-13
  • 打赏
  • 举报
回复
libin_ftsafe(子陌红尘) 速度好快啊。
bcsky 2006-01-13
  • 打赏
  • 举报
回复
谢谢 libin_ftsafe(子陌红尘)
几乎每次都你帮的忙
又积累了一点
子陌红尘 2006-01-13
  • 打赏
  • 举报
回复
create table t(employeeid int,jiab int,appmonth int,depart char(1))
insert into t select 1,2,10,'a'
insert into t select 1,1,11,'b'
insert into t select 1,2,12,'c'
insert into t select 2,1,10,'a'
insert into t select 2,1,11,'b'
insert into t select 2,1,12,'c'

declare @s varchar(8000)
set @s='select employeeid'
select @s=@s+',['+rtrim(appmonth)+'月部门]=max(case appmonth when '+rtrim(appmonth)+' then depart end)'
+',['+rtrim(appmonth)+'月天数]=sum(case appmonth when '+rtrim(appmonth)+' then jiab end)'
from t group by appmonth order by appmonth
set @s=@s+' from t group by employeeid order by employeeid'
exec(@s)

/*
employeeid 10月部门 10月天数 11月部门 11月天数 12月部门 12月天数
----------- -------- -------- -------- -------- -------- -----------
1 a 2 b 1 c 2
2 a 1 b 1 c 1
*/

drop table t
bcsky 2006-01-13
  • 打赏
  • 举报
回复
是纵表变横表
不好意思说错了

27,579

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 应用实例
社区管理员
  • 应用实例社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧