当前位置: 代码迷 >> Sql Server >> sql 行转列解决方法
  详细解决方案

sql 行转列解决方法

热度:28   发布时间:2016-04-24 10:22:40.0
sql 行转列

有如下表:
年份(int)                            说明(nvarchar(100))
1999                                  1999说明1
1999                                  1999说明2
2000                                   2000说明1
2000                                   2000说明2
2001                                   2001说明1
2001                                   2001说明2
2001                                   2001说明3


需要显示的结果如下

   1999                                         2000                                     2001
   1999说明1                               2000说明1                     2001说明1
   1999说明2                               2000说明2                     2001说明2
   null                                                null                              2001说明3

------解决方案--------------------
----------------------------------------------------------------
-- Author  :fredrickhu(小F,向高手学习)
-- Date    :2014-07-11 16:09:39
-- Version:
--      Microsoft SQL Server 2012 - 11.0.2100.60 (Intel X86) 
-- Feb 10 2012 19:13:17 
-- Copyright (c) Microsoft Corporation
-- Enterprise Edition: Core-based Licensing on Windows NT 6.1 <X86> (Build 7601: Service Pack 1)
--
----------------------------------------------------------------
--> 测试数据:[tb]
if object_id('[tb]') is not null drop table [tb]
go 
create table [tb]([年份] int,[说明] varchar(9))
insert [tb]
select 1999,'1999说明1' union all
select 1999,'1999说明2' union all
select 2000,'2000说明1' union all
select 2000,'2000说明2' union all
select 2001,'2001说明1' union all
select 2001,'2001说明2' union all
select 2001,'2001说明3'
--------------开始查询--------------------------
declare @s nvarchar(4000)
set @s=''
Select     @s=@s+','+quotename([年份])+'=max(case when [年份]=' +ltrim(年份)+ ' then [说明] else null end)'
from (select px=row_number()over(partition by 年份 order by getdate()),* from tb) as t group by 年份
select @s=stuff(@s,1,1,'')
exec('select '+@s+' from (select px=row_number()over(partition by 年份  order by getdate()),* from tb) as t group by px')
----------------结果----------------------------
/* 1999      2000      2001
--------- --------- ---------
1999说明1   2000说明1   2001说明1
1999说明2   2000说明2   2001说明2
NULL      NULL      2001说明3
  相关解决方案