试图找出动态转动表上的日期字段下表中的最佳途径。 问题是这些日期更改,所以我不能硬编码它们枢轴声明。
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
由于您使用的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拨弄演示 。
但是,如果他们是未知的,那么你就需要使用动态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拨弄演示 。
两种查询的结果是:
| 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) |
试试这个
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')