我有一个以下格式的表格
Country_Code | 1960 | 1961 | 1962 | ..... | 2011 ------------------------------------------------ IND | va11 | va12 | va13 | ..... | va1x AUS | va21 | va22 | va23 | ..... | va2x ENG | va31 | va32 | va33 | ..... | va3x
我想将其转换为以下格式
Country_Code | Year | Value --------------------------- IND | 1960 | va11 IND | 1961 | va12 IND | 1962 | va13 . . IND | 2011 | va1x AUS | 1960 | va21 AUS | 1961 | va22 AUS | 1962 | va23 . . AUS | 2011 | va2x ENG | 1960 | va31 ENG | 1961 | va32 ENG | 1962 | va33 . . ENG | 2011 | va3x
如何通过sql查询或sql服务器程序集实现此目的?
您可以完成UNPIVOT。如果您知道已知的列数,则可以对值进行硬编码:
UNPIVOT
select Country_Code, year, value from yourtable unpivot ( value for year in ([1960], [1961], [1962], [2011]) ) u
参见带有演示的SQL Fiddle
如果列数未知,则可以使用动态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)
您甚至可以使用UNION ALL:
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