我如何查询 sql 的最新记录日期,但如果该记录有一条消息 return 该记录

how do I query sql for a latest record date but if the record has a message return that reocrd

根据这个例子table我需要第 2 行和第 3 行。

这个查询应该select你需要什么:

Select T.* 
from your_table T
Inner join (


Select compId, max(date) as maxDate
From your_table
Where message is not null 
Group by compId
Union 
Select compId, max(date) as maxDate
From your_table
Where compId not in (select compId from your_table where message is not null )
Group by compId

) Last on Last .compId = T.compId and Last.maxDate = T.date

我了解到您想要每个 compID 的最新非空消息,或者如果所有消息都为空则需要最新消息。

如果是这样,您可以使用 window 函数:

select id, compID, date, message
from (
    select 
        t.*,
        row_number() over(
            partition by compID 
            order by case when message is not null then 0 else 1 end, date desc
        ) rn
    from mytable t
) t
where rn = 1
order by id

Demo on DB Fiddle:

id | compID | date       | message    
-: | :----- | :--------- | :----------
 2 | B      | 2020-03-27 | null       
 3 | A      | 2020-03-22 | Hello World
SELECT t.* 
FROM #tmp t JOIN (SELECT CompID, MAX(Date) AS DateMax, MAX(CASE WHEN Message IS NOT NULL THEN ID END) AS MsgMaxID
    FROM #tmp 
    GROUP BY CompID) agt ON (t.ID = agt.MsgMaxID OR (agt.MsgMaxID IS NULL AND t.CompID = agt.CompID AND t.Date = agt.DateMax))