考虑名为 [tbl_event] 的表中的以下示例数据
ID protocolID SubjectID imgDate1
-- ---------- --------- ----------
1 0388813 0001 2011-01-01
2 0388813 0001 1995-06-30
3 0388813 0001 2012-03-11
4 0388813 0001 2000-01-01
5 0388813 0002 2013-05-06
6 0388814 0001 2013-04-14
由于我们很幸运有一个 [ID] 字段,我们可以使用“自连接”技巧来生成一个按 [protocolID]+[SubjectID] 排序的列表:
SELECT ID, protocolID, SubjectID, imgDate1, COUNT(*) AS Rank
FROM
(
SELECT t1.*
FROM
tbl_event t1
INNER JOIN
tbl_event t2
ON t2.protocolID=t1.protocolID
AND t2.SubjectID=t1.SubjectID
AND t2.ID<=t1.ID
)
GROUP BY ID, protocolID, SubjectID, imgDate1
...生产...
ID protocolID SubjectID imgDate1 Rank
-- ---------- --------- ---------- ----
1 0388813 0001 2011-01-01 1
2 0388813 0001 1995-06-30 2
3 0388813 0001 2012-03-11 3
4 0388813 0001 2000-01-01 4
5 0388813 0002 2013-05-06 1
6 0388814 0001 2013-04-14 1
在这种情况下,我们可以稍微修改一下,给我们(最终的)列名:
SELECT ID, protocolID, SubjectID, imgDate1, "Date" & Format(COUNT(*), "00") AS ColName
FROM
(
SELECT t1.*
FROM
tbl_event t1
INNER JOIN
tbl_event t2
ON t2.protocolID=t1.protocolID
AND t2.SubjectID=t1.SubjectID
AND t2.ID<=t1.ID
)
GROUP BY ID, protocolID, SubjectID, imgDate1
...生产...
ID protocolID SubjectID imgDate1 ColName
-- ---------- --------- ---------- -------
1 0388813 0001 2011-01-01 Date01
2 0388813 0001 1995-06-30 Date02
3 0388813 0001 2012-03-11 Date03
4 0388813 0001 2000-01-01 Date04
5 0388813 0002 2013-05-06 Date01
6 0388814 0001 2013-04-14 Date01
如果我们将该查询保存为 [tbl_event_xtab_base] 那么我们可以在交叉表查询中使用它:
TRANSFORM Max(tbl_event_xtab_base.[imgDate1]) AS MaxOfimgDate1
SELECT tbl_event_xtab_base.[protocolID], tbl_event_xtab_base.[SubjectID]
FROM tbl_event_xtab_base
GROUP BY tbl_event_xtab_base.[protocolID], tbl_event_xtab_base.[SubjectID]
PIVOT tbl_event_xtab_base.[ColName];
...生产...
protocolID SubjectID Date01 Date02 Date03 Date04
---------- --------- ---------- ---------- ---------- ----------
0388813 0001 2011-01-01 1995-06-30 2012-03-11 2000-01-01
0388813 0002 2013-05-06
0388814 0001 2013-04-14