A表month ID SL
201201 2 5
201202 2 4
201202 3 5
201203 3 6
201203 4 7
201204 4 9当查询 ID 在 201201到201204形成的月份交叉表,月名称当成字段名,关键就是表头(月份)是根据查询动态生成的ID 201201 201202 201203 201204
2 5 4 0 0
3 0 5 6 0
4 0 0 7 9
201201 2 5
201202 2 4
201202 3 5
201203 3 6
201203 4 7
201204 4 9当查询 ID 在 201201到201204形成的月份交叉表,月名称当成字段名,关键就是表头(月份)是根据查询动态生成的ID 201201 201202 201203 201204
2 5 4 0 0
3 0 5 6 0
4 0 0 7 9
from A
pivot max(SL) for [month] in ([201201],[201202],[201203],[201204])
from A
pivot max(SL) for [month] in ([201201],[201202],[201203],[201204])
--> 测试数据:[test]
if object_id('[test]') is not null
drop table [test]
create table [test](
[month] varchar(6),
[ID] int,
[SL] int
)
insert [test]
select '201201',2,5 union all
select '201202',2,4 union all
select '201202',3,5 union all
select '201203',3,6 union all
select '201203',4,7 union all
select '201204',4,9
godeclare @str varchar(max)
set @str=''
select @str=@str+',['+[month]+']=sum(case when [month]='+QUOTENAME([month],'''')+
' then [SL] else 0 end)'
from test
group by [month]
exec('select [ID]'+@str+' from test group by [ID]')/*
ID 201201 201202 201203 201204
----------- ----------- ----------- ----------- -----------
2 5 4 0 0
3 0 5 6 0
4 0 0 7 9(3 行受影响)
*/我猜你真实也不只这几个数据啥 动态实现吧
--新方法
select * from test pivot (max([SL]) for [month] in([201201],[201202],[201203],[201204]))b
/*
ID 201201 201202 201203 201204
----------- ----------- ----------- ----------- -----------
2 5 4 NULL NULL
3 NULL 5 6 NULL
4 NULL NULL 7 9(3 行受影响)
*/--自己吧null处理一下