我有这个数据库表。
dbo.tblSites
| Site_Code | Site Name |
A Aaaaaa
B Bbbbbb
C Cccccc
D Dddddd
这是另一张表
dbo.Server
| Site_Code | ServerName | Status | Timestamp |
A QQQ OK 01/02/2016 10:00:00.000
A QQQ OK 01/02/2016 10:00:03.000
A QQQ Critical 01/02/2016 10:00:05.000
A WWW Critical 01/02/2016 10:00:02.000
A WWW Critical 01/02/2016 10:00:05.000
A WWW OK 01/02/2016 10:00:06.000
A EEE OK 01/02/2016 10:00:05.000
A EEE OK 01/02/2016 10:00:07.000
A EEE Critical 01/02/2016 10:00:08.000
B QQQ OK 01/02/2016 10:00:00.000
B QQQ OK 01/02/2016 10:00:03.000
B QQQ Critical 01/02/2016 10:00:05.000
B WWW Critical 01/02/2016 10:00:02.000
B WWW Critical 01/02/2016 10:00:05.000
B WWW OK 01/02/2016 10:00:06.000
B EEE OK 01/02/2016 10:00:05.000
B EEE OK 01/02/2016 10:00:07.000
B EEE OK 01/02/2016 10:00:08.000
我需要获取所有站点代码并将其作为列 我还需要在列下面列出服务器的“最新”状态
| ServerName | SiteCode-A | SiteCode-B | SiteCode-C | SiteCode-D |
QQQ Critical Critical No Data Found No Data Found
WWW OK OK No Data Found No Data Found
EEE Critical OK No Data Found No Data Found
答案 0 :(得分:1)
您可以使用dynamic crosstab执行此操作:
DECLARE @sql NVARCHAR(MAX) = ''
SELECT @sql =
'SELECT
ServerName' + CHAR(10)
SELECT @sql = @sql +
' , ISNULL(MAX(CASE WHEN Site_Code = ''' + Site_Code + '''THEN Status END), ''No Data Found'') AS ' + QUOTENAME('SiteCode-'+Site_Code) + CHAR(10)
FROM tblSites
ORDER BY Site_Code
SELECT @sql = @sql +
'FROM (
SELECT *, rn = ROW_NUMBER() OVER(PARTITION BY Site_Code, ServerName ORDER BY Timestamp DESC)
FROM [Server]
) t
WHERE rn = 1
GROUP BY ServerName
ORDER BY ServerName'
PRINT @sql
EXEC sp_executesql @sql