我在 SQL Server 2000 数据库中有以下表:
掌握
MasterID | Details | [other fields]
=====================================
PK (int) | Free text | ...
日志表
LogID | MasterID | UserID | LogDate | LogText
==========================================================
PK (int) | FK (int) | VarChar(2)| Date stamp | Free text
每个主记录可能有许多日志条目。
我有一个查询,它为每个主行提取最近的三个关联日志条目,如下所示。请注意,执行适当的转换和格式化以实现LogData
连接(为清楚起见省略):
SELECT
M.MasterID, M.Details, L.LogDate + L.UserID + L.LogText AS LogData
FROM
MasterTable M
INNER JOIN
LogTable L ON M.MasterID = L.MasterID
AND L.LogID IN (SELECT TOP 3 LogID FROM LogTable
WHERE MasterID = M. MasterID ORDER BY LogDate DESC)
这会产生如下输出:
MasterID | Details | LogData
========================================================
1 | First | 05/11/2012 AB Called Client
2 | Second | 08/11/2012 CD Client Visit
2 | Second | 07/11/2012 CD Called Client
2 | Second | 05/11/2012 AB Called Client
我需要实现的是将第二个表中的数据显示为输出中的列,所有数据都针对每条主记录进行报告,从而避免重复数据。像这样:
MasterID | Details | LogData1 | LogData2 | LogData3
===========================================================================================================
1 | First | 05/11/2012 AB Called Client | (null) | (null)
2 | Second | 08/11/2012 CD Client Visit | 07/11/2012 CD Called Client | 05/11/2012 AB Called Client
请注意,在现实世界的需求中,此解决方案将是扁平化 5 个表的一部分,输出由大约 20,000 行和 90 列数据组成。
提前致谢。