SQL Server 2008 : Convert column value to row

后端 未结 1 811
日久生厌
日久生厌 2020-12-10 23:36

I have a table in the following format

Country_Code | 1960 | 1961 | 1962 | ..... | 2011
------------------------------------------------
IND          | va11 | va1         


        
相关标签:
1条回答
  • 2020-12-11 00:14

    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

    0 讨论(0)
提交回复
热议问题