当前位置: 代码迷 >> Sql Server >> sql多条记录合并(应该不是行转列的有关问题)
  详细解决方案

sql多条记录合并(应该不是行转列的有关问题)

热度:43   发布时间:2016-04-24 10:02:49.0
sql多条记录合并(应该不是行转列的问题)
本帖最后由 easyeat 于 2014-08-27 18:11:49 编辑

请问下,怎么把第一张表合并成第二张表的这个样式

SQL语句如下:
drop table #tb
create table #tb (ID int,YearData int,Col_1 int,Col_2 int)
insert into #tb select 1001,2013,39,31
union
select 1002,2013,32,32
union
select 1003,2014,35,35
union
select 1001,2014,45,42
union
select 1002,2014,45,42
union
select 1001,2015,51,52
select * from #tb

------解决方案--------------------
典型的行列转换

select
    id,
    max(case when YearData=2013 then col_1 else 0 end) as '2013年1月',
    max(case when YearData=2013 then col_2 else 0 end) as '2013年2月',
    max(case when YearData=2014 then col_1 else 0 end) as '2014年1月',
    max(case when YearData=2014 then col_2 else 0 end) as '2014年2月',
....--剩下的自己补充
from
   #tb
group by
   id

------解决方案--------------------
 select ID ,ISNULL(p.[2013年1月],0)as [2013年1月],
 ISNULL(p.[2013年2月],0)as [2013年2月],
 ISNULL(p.[2014年1月],0)as [2014年1月],
 ISNULL(p.[2014年1月],0)as [2013年2月],
 ISNULL(p.[2015年1月],0)as [2015年1月],
 ISNULL(p.[2015年1月],0)as [2015年2月]
  from 
 (select ID ,
  sum(case yeardata when '2013' then col_1 end) as [2013年1月],
  sum(case yeardata when '2013' then col_2 end) as [2013年2月],
  sum(case yeardata when '2014' then col_1 end) as [2014年1月],
  sum(case yeardata when '2014' then col_2 end) as [2014年2月],
  sum(case yeardata when '2015' then col_1 end) as [2015年1月],
  sum(case yeardata when '2015' then col_2 end) as [2015年2月]
    from #tb
  group by ID) as p
   这种2013年2月  列名 坑爹啊
  相关解决方案