Aggregate functions in WHERE clause in SQLite

后端 未结 4 1674
青春惊慌失措
青春惊慌失措 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 06:46

    you can simply do

    SELECT *, max(timestamp) FROM table

    Edit: As aggregate function can't be used like this so it gives error. I guess what SquareCog had suggested was the best thing to do

    SELECT * FROM table WHERE timestamp = (select max(timestamp) from table)
    
    0 讨论(0)
  • 2021-02-08 06:50
    SELECT * from foo where timestamp = (select max(timestamp) from foo)
    

    or, if SQLite insists on treating subselects as sets,

    SELECT * from foo where timestamp in (select max(timestamp) from foo)
    
    0 讨论(0)
  • 2021-02-08 06:52

    There are many ways to skin a cat.

    If you have an Identity Column that has an auto-increment functionality, a faster query would result if you return the last record by ID, due to the indexing of the column, unless of course you wish to put an index on the timestamp column.

    SELECT * FROM TABLE ORDER BY ID DESC LIMIT 1
    
    0 讨论(0)
  • 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).

    0 讨论(0)
提交回复
热议问题