通过DATETIME或NULL获取最新记录

时间:2014-04-28 21:05:03

标签: sql sql-server sql-server-2008-r2

我有以下查询:

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

我得到以下结果:

enter image description here

我知道我做错了,但我想要的是最新约会的记录。如果timestampOut为null,那么我想要那条记录。最后我只想要1条记录而不是2条。

谢谢!

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