我有这个SQL:
SELECT a.ID,
a.title,
a.section,
a.name,
l.User AS CreatedBy,
IIf(IsNull(l.Time),
Null, DateAdd ( "s", l.time, #03/01/1980# )) AS CreatedAt
FROM (
Reports AS a
LEFT JOIN AuditLog AS l ON a.ID = l.ID
)
LEFT JOIN
(SELECT TOP 1 Min([time]) AS Mintime,
URN FROM AuditLog GROUP BY ID)
AS t ON (l.time = t.mintime) AND (l.ID = t.ID)
WHERE a.Active = 'Y';
查询有效,但返回重复记录(因为1个报告有多个审核日志)。我只希望这返回一个ID
记录,显示最早的审核时间(因此mintime
是什么)。我添加了TOP 1
,但似乎没有任何改变。我也考虑了GROUP BY ID
,但对于如何仍然显示title
等有点困惑,因为它抱怨它们没有聚合。
当前输出:
ID title section CreatedBy CreatedAt
Z.test1 Example 1 Ex User1 01/01/2012
Z.test5 Example 5 Ex User2 02/03/2012
Z.test6 Example 6 Ex User3 03/06/2012
Z.test6 Example 6 Ex User4 02/01/2000
预期产出:
ID title section CreatedBy CreatedAt
Z.test1 Example 1 Ex User1 01/01/2012
Z.test5 Example 5 Ex User2 02/03/2012
Z.test6 Example 6 Ex User4 02/01/2000
如上所示,仅显示Z.test6的最早记录,而不是所有结果。
尝试新查询:
SELECT a.ID, a.title, a.section, a.name, l.User AS CreatedBy, IIf(IsNull(l.Time), Null, DateAdd ( "s", l.time, #03/01/1980# )) AS CreatedAt
FROM (
Reports AS a
LEFT JOIN (
SELECT ID, Min([time]) AS Mintime FROM AuditLog GROUP BY ID
) AS t ON (l.ID = t.ID)
LEFT JOIN AuditLog AS l ON (a.ID = l.ID AND t.mintime = l.time)
)
WHERE a.Active = 'Y'
答案 0 :(得分:3)
交换连接顺序,只选择分组所需的子查询“t”中的最小必需字段。像这样:
SELECT a.ID,
a.title,
a.section,
a.name,
l.User AS CreatedBy,
IIf(IsNull(l.Time),
Null, DateAdd ( "s", l.time, #03/01/1980# )) AS CreatedAt
FROM (
Reports AS a
LEFT JOIN (SELECT ID, Min([time]) AS Mintime
FROM AuditLog GROUP BY ID) AS t
ON (a.ID = t.ID)
LEFT JOIN AuditLog AS l
ON (t.ID = l.ID AND t.mintime = l.time)
)
WHERE a.Active = 'Y';