SQL高桌到数据透视表

时间:2014-02-18 18:20:21

标签: sql sql-server pivot

我的输出看起来像

ID | Version | Date | Value | Value Type
1  | 1       | 2012 | 1     | x
1  | 1       | 2012 | 1.5   | y
1  | 2       | 2012 | 2.3   | x
1  | 2       | 2012 | 1.7   | y

我希望输出看起来像

ID | Version | Date | X   | Y
1  | 1       | 2012 | 1   | 1.5   
1  | 2       | 2012 | 2.3 | 1.7       

谢谢!

1 个答案:

答案 0 :(得分:3)

由于您使用的是SQL Server,因此有多种方法可以获得结果。

您可以将聚合函数与CASE表达式一起使用:

select id, version, date,
  max(case when valuetype = 'X' then value end) X,
  max(case when valuetype = 'Y' then value end) Y
from yourtable
group by id, version, date;

请参阅SQL Fiddle with Demo

从SQL Server 2005开始,引入了PIVOT功能。如果您的值有限,则可以对查询进行硬编码:

select id, version, date, X, Y
from
(
  select id, version, date, valuetype, value
  from yourtable
) d
pivot
(
  max(value)
  for valuetype in (X, Y)
) p;

SQL Fiddle with Demo。最后,如果您有未知数量的值,那么您将需要使用动态SQL来获得结果:

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

select @cols = STUFF((SELECT  ',' + QUOTENAME(ValueType) 
                    from yourtable
                    group by ValueType
                    order by ValueType
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = N'SELECT id, version, date,' + @cols + N' 
            from 
            (
              select id, version, date, valuetype, value
              from yourtable
            ) x
            pivot 
            (
                max(value)
                for valuetype in (' + @cols + N')
            ) p '

execute sp_executesql @query;

请参阅SQL Fiddle with Demo