具有多列的MS Access交叉表查询?

时间:2015-10-01 02:39:51

标签: ms-access ms-access-2010

在交叉表查询中获取多列的最佳方法是什么?我有下表:

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 个答案:

答案 0 :(得分: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];