Aggregate functions in WHERE clause in SQLite

后端 未结 4 1672
青春惊慌失措
青春惊慌失措 2021-02-08 06:29

Simply put, I have a table with, among other things, a column for timestamps. I want to get the row with the most recent (i.e. greatest value) timestamp. Currently I\'m doing th

4条回答
  •  礼貌的吻别
    2021-02-08 07:01

    I think I've answered this question 5 times in the past week now, but I'm too tired to find a link to one of those right now, so here it is again...

    SELECT
         *
    FROM
         table T1
    LEFT OUTER JOIN table T2 ON
         T2.timestamp > T1.timestamp
    WHERE
         T2.timestamp IS NULL
    

    You're basically looking for the row where no other row matches that is later than it.

    NOTE: As pointed out in the comments, this method will not perform as well in this kind of situation. It will usually work better (for SQL Server at least) in situations where you want the last row for each customer (as an example).

提交回复
热议问题