我有以下查询:
SELECT DISTINCT
c.id, creator, ls.name, ld.timestampOut
FROM
countermeasures c
LEFT OUTER JOIN
lifecycleDetails ld ON ld.documentId = c.id
LEFT OUTER JOIN
lifecycleState ls ON ls.id = ld.lifecycleStatus
WHERE
ld.timestampOut = (SELECT MAX(timestampOut) from lifecycleDetails)
OR ld.timestampOut IS NULL
我得到以下结果:
我知道我做错了,但我想要的是最新约会的记录。如果timestampOut为null,那么我想要那条记录。最后我只想要1条记录而不是2条。
谢谢!
答案 0 :(得分:2)
如果您使用的是SQL Server,则可以使用row_number()
来实现此目的:
SELECT id, creator, name, timestampOut
FROM (SELECT c.id, creator, ls.name, ld.timestampOut,
row_number() over (partition by id order by (case when ld.timestampOut is null then 1 else 2 end),
timestampOut desc
) as seqnum
FROM countermeasures c
LEFT OUTER JOIN lifecycleDetails ld ON ld.documentId = c.id
LEFT OUTER JOIN lifecycleState ls ON ls.id = ld.lifecycleStatus
) t
WHERE seqnum = 1;
答案 1 :(得分:0)
SELECT DISTINCT top 1
c.id, creator, ls.name, ld.timestampOut
...
WHERE
ld.timestampOut = (SELECT MAX(timestampOut) from lifecycleDetails)
OR ld.timestampOut IS NULL
ORDER BY timestampOut