尝试找出在下表中的日期字段上动态旋转表的最佳方法。问题是这些日期发生了变化,所以我不能在枢轴声明中对它们进行硬编码。
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
答案 0 :(得分: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:
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)
两个查询的结果是:
| 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) |
答案 1 :(得分: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')