你可以用PIVOT
这个。如果您知道所有值,则可以对其进行硬编码:
select *
from
(
select rowid, dimension, value
from yourtable
) src
pivot
(
max(value)
for dimension in ([Country], [Year], [GDP], [Population])
) piv
请参阅带有演示的 SQL Fiddle
或者你们中的一些人无权访问该PIVOT
函数,那么您可以使用带有 a 的聚合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
如果您有未知数量的值,则可以使用动态 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