SQL Server 2008 : Convert column value to row

此生再无相见时 提交于 2019-11-28 11:49:43

You can be done with UNPIVOT. If you have a known number of columns then you can hard-code the values:

select Country_Code, year, value
from yourtable
unpivot
(
  value 
  for year in ([1960], [1961], [1962], [2011])
) u

See SQL Fiddle with Demo

If you have an unknown number of columns, then you can use dynamic sql:

DECLARE @colsUnpivot AS NVARCHAR(MAX),
   @query  AS NVARCHAR(MAX)

select @colsUnpivot = stuff((select ','+quotename(C.name)
         from sys.columns as C
         where C.object_id = object_id('yourtable') and
               C.name != 'Country_Code'
         for xml path('')), 1, 1, '')

set @query 
  = 'select country_code, year, value
     from yourtable
     unpivot
     (
        value
        for year in ('+ @colsunpivot +')
     ) u'

exec(@query)

See SQL Fiddle with Demo

Of you can even use a UNION ALL:

select country_code, '1960' year, 1960 value
from yourtable
union all
select country_code, '1961' year, 1961 value
from yourtable
union all
select country_code, '1962' year, 1962 value
from yourtable
union all
select country_code, '2011' year, 2011 value
from yourtable

See SQL Fiddle with Demo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!