2015-10-01 94 views
1

在交叉表查詢中獲取多列的最佳方式是什麼?我有以下表格:帶有多個列的MS Access交叉表查詢?

ID Name Topic Date 
123 John Define 9/30/2015 
123 John Measure 10/30/2015 
123 John Analyze 11/30/2015 
321 Mary Measure 8/28/2015 
321 Mary Define 7/15/2015 
321 Mary Define 6/15/2015 

這是我在尋找的結果:

ID Name Define Define Date Measure Measure Date Analyze Analyze Date 
123 John  1  9/30/2015 1  10/30/2015  1  11/30/2015 
321 Mary  2  7/15/2015 1  8/28/2015  

我創建了一個交叉表查詢轉動的主題和列數,但我還沒有想出如何爲計數旁邊的日期添加另一列。

我可以有不同日期的多個主題,但我會使用Max來獲取最新日期。謝謝!

回答

1

只需在GROUP BY查詢中運行條件聚合即可轉置數據。因爲您不想將行值轉換爲列,所以交叉表不會有幫助。相反,您希望根據行值定義列。

SELECT [ID], [Name], 
     Count(IIF(Topic='Define', Topic, Null)) As [Define], 
     Max(IIF(Topic='Define', [Date], Null)) As [Define Date], 
     Count(IIF(Topic='Measure', Topic, Null)) As [Measure], 
     Max(IIF(Topic='Measure', [Date], Null)) As [Measure Date], 
     Count(IIF(Topic='Analyze', Topic, Null)) As [Analyze], 
     Max(IIF(Topic='Analyze', [Date], Null)) As [Analyze Date] 
FROM TableName 
GROUP BY [ID], [Name];