我有如下表所示的表格。我需要获取与每个不同元素的最大日期时间戳对应的值,并使用SQL Server 2005或更高版本将行转换为列。列名值(即列A1,A2,A3是动态的,可根据可用数据而变化)
基表(来自结果查询)
Id Name Value DateTimeStamp
--------------------------------------
1 A1 5 Nov 14 2011 03:12:12:947PM
1 A1 6 Nov 15 2011 03:12:12:947PM
1 A2 7 Nov 14 2011 03:12:12:947PM
1 A2 8 Nov 15 2011 03:12:12:947PM
1 A3 9 Nov 14 2011 03:12:12:947PM
2 A3 10 Nov 15 2011 03:12:12:947PM
2 A1 1 Nov 14 2011 03:12:12:947PM
2 A1 2 Nov 15 2011 03:12:12:947PM
2 A2 3 Nov 14 2011 03:12:12:947PM
2 A2 4 Nov 15 2011 03:12:12:947PM
2 A3 5 Nov 14 2011 03:12:12:947PM
2 A3 6 Nov 15 2011 03:12:12:947PM
期望的输出:
Id A1 A2 A3
---------------
1 6 8 10
2 2 4 6
答案 0 :(得分:0)
您可以使用dynamic crosstab:
执行此操作DECLARE @sql NVARCHAR(MAX) = ''
SELECT @sql =
'SELECT
Id' + CHAR(10)
SELECT @sql = @sql +
', MAX(CASE WHEN Name = ''' + Name + ''' THEN Value END) AS ' + QUOTENAME(Name) + CHAR(10)
FROM (SELECT DISTINCT Name FROM tbl) t
ORDER BY Name
SELECT @sql = @sql +
'FROM (
SELECT *,
RN = ROW_NUMBER() OVER(PARTITION BY Id, Name ORDER BY DateTimeStamp DESC)
FROM tbl
) t
WHERE Rn = 1
GROUP BY Id
ORDER BY Id'
EXEC sp_executesql @sql