Home > Blockchain >  How to get just the newest row from a group where the date is expressed as a string
How to get just the newest row from a group where the date is expressed as a string

Time:05-24

I have a database using sqlite3 and one of the columns is storing a date (rfc3339 format) as TEXT.

My database is storing daily values for various objects. In the example below, A and B.

id obj date value
13 A 2022-05-22T20:02:20.465515Z 413
223 A 2022-05-23T09:23:39.591774Z 517
25 B 2022-05-22T20:02:20.469512Z 963
948 B 2022-05-23T09:23:39.600809Z 1124

What I want to do is to select just the newest date for each object. The objects are referenced in another database. The desired result would be:

id obj date value
223 A 2022-05-23T09:23:39.591774Z 517
948 B 2022-05-23T09:23:39.600809Z 1124

If I have hundreds of entries for the obj A, B, C... how can I select just the newest one for each object? (that is, grouped by the value on the column obj)

CodePudding user response:

You can use ROW_NUMBER() function such as

SELECT id, obj, date, value
  FROM ( SELECT t.*,
               ROW_NUMBER() OVER 
               (PARTITION BY obj 
                    ORDER BY strftime('%Y-%m-%dT%H:%M:%S.%fZ', date) DESC) AS rn 
           FROM t ) AS tt 
 WHERE rn = 1

CodePudding user response:

With simple aggregation:

SELECT id, obj, MAX(date) AS date, value
FROM tablename
GROUP BY obj;

SQLite returns for each obj the row with the most recent date.
For reference: Bare columns in an aggregate query

  • Related