2

试图找出在下表中的日期字段上动态旋转表格的最佳方法。问题是这些日期发生了变化,所以我不能在数据透视语句中对它们进行硬编码。

id value date
1  55    2012-12-29 00:00:00:00
1  54    2012-10-29 00:00:00:00
1  89    2013-02-02 00:00:00:00
2  45    2012-12-29 00:00:00:00
2  54    2012-10-29 00:00:00:00
4  78    2012-12-29 00:00:00:00
4  90    2012-10-29 00:00:00:00
4  23    2012-10-29 00:00:00:00

我希望输出看起来像这样

id 2012-12-29 00:00:00:00 2012-10-29 00:00:00:00 2013-02-02 00:00:00:00
1   55                    54                     89
2   45                    54                     null
4   78                    90                     23
4

2 回答 2

5

由于您使用的是 SQL Server,因此您可以使用该PIVOT功能。

如果您的值是已知的,那么您可以对这些值进行硬编码:

select *
from
(
  select id, value, date
  from yourtable
) src
pivot
(
  max(value)
  for date in ([2012-12-29], [2012-10-29], [2013-02-02])
) piv

请参阅SQL Fiddle with Demo

但如果它们是未知的,那么您将需要使用动态 sql:

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

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

set @query = 'SELECT id, ' + @cols + ' from 
             (
                select id, value, convert(varchar(50), date, 120) date
                from yourtable
            ) x
            pivot 
            (
                max(value)
                for date in (' + @cols + ')
            ) p '

execute(@query)

请参阅SQL Fiddle with Demo

两个查询的结果是:

| ID | 2012-10-29 00:00:00 | 2012-12-29 00:00:00 | 2013-02-02 00:00:00 |
------------------------------------------------------------------------
|  1 |                  54 |                  55 |                  89 |
|  2 |                  54 |                  45 |              (null) |
|  4 |                  90 |                  78 |              (null) |
于 2013-02-15T20:20:53.950 回答
0

尝试这个

DECLARE @columns VARCHAR(8000)

-- set columns for pivot
SELECT @columns = COALESCE(@columns + ',[' + cast([date] as varchar(50)) + ']', '[' + cast([date] as varchar(50))+ ']')         
    FROM  TableName

EXEC(' SELECT *, ' +  @columns + ' FROM 
       (
           SELECT * FROM TableName
       ) As a
       PIVOT (MAX(value) FOR DATE IN (' + @columns + ') ) As P')
于 2013-02-15T20:21:57.460 回答