部分行到列

时间:2012-11-10 23:21:35

标签: sql sql-server sql-server-2008 pivot

有人可以指导我如何转动我的数据。我有:

RowID Dimension Value
1 Country Italy
1 Year 2011
1 GDP 4
1 Population 6
2 Country Spain
2 Year 2011
2 GDP 7
2 Population 5

我想以这样的方式:

RowID Country Year GDP Population
1 Italy 2011 4 6
2 Spain 2011 7 5

P.S。我使用的是MS SQL Server 2008 R2 Express Edition。我试图使用PIVOT,但它返回了许多行为NULL,所以我无法弄清楚。

1 个答案:

答案 0 :(得分:1)

您可以使用PIVOT。如果您知道所有值,则可以对其进行硬编码:

select *
from
(
  select rowid, dimension, value
  from yourtable
) src
pivot
(
  max(value)
  for dimension in ([Country], [Year], [GDP], [Population])
) piv

请参阅SQL Fiddle with Demo

或者您无法访问PIVOT功能,那么您可以使用CASE的聚合:

select rowid,
  max(case when dimension = 'country' then value end) country,
  max(case when dimension = 'Year' then value end) Year,
  max(case when dimension = 'GDP' then value end) GDP,
  max(case when dimension = 'Population' then value end) Population
from yourtable
group by rowid

请参阅SQL Fiddle with Demo

如果您有不确定数量的值,则可以使用动态sql:

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

select @cols = STUFF((SELECT distinct ',' + QUOTENAME(Dimension) 
                    from yourtable
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = 'SELECT rowid, ' + @cols + ' from 
             (
                select rowid, dimension, value
                from yourtable
            ) x
            pivot 
            (
                max(value)
                for dimension in (' + @cols + ')
            ) p '

execute(@query)

请参阅SQL Fiddle with Demo