How can I select the set of rows where each item has the greatest timestamp?

前端 未结 3 1478
天涯浪人
天涯浪人 2020-12-22 00:23

Using Sqlite, I\'d like to fetch the collection of rows each with the greatest timestamp. The table contains the properties of items, which are key-value pairs and timestamp

相关标签:
3条回答
  • 2020-12-22 00:38

    In SQLite 3.7.11 or later, you can simply use MAX() to select one row from a group:

    SELECT key, value, MAX(timestamp)
    FROM Properties
    WHERE thing = 'watermelon'
    GROUP BY key;
    
    0 讨论(0)
  • 2020-12-22 00:44

    Use HAVING for simple and readable solution:

    SQLFiddleDemo

    SELECT *
    FROM Properties
    WHERE thing = "watermelon"
    GROUP BY thing, key
    HAVING timestamp = MAX(timestamp)
    
    0 讨论(0)
  • 2020-12-22 00:53

    Tweaking the query found here, I've come up with the following:

    SELECT a.* 
    FROM Properties AS a 
    INNER JOIN (
      SELECT key, MAX(timestamp) AS max_timestamp 
      FROM Properties 
      WHERE thing='watermelon' 
      GROUP BY key) b 
    ON a.key = b.key AND a.timestamp = b.max_timestamp 
    WHERE thing='watermelon';
    

    Seems to work, though I'd be interested in comments the pros/cons of this query.

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