I\'d like to know if it\'s possible to do the following using a single sqlite statement:
My table looks something like this:
|AnId|UserId|SomeDate|So
As of Sqlite 3.25 window functions are supported. See https://www.sqlite.org/windowfunctions.html for details.
I needed to fetch the second row for each "object" in a table with a 1 to many relationship to the "object" table.
Usually in SQL this will be done using ROW_NUMBER() OVER(PARTITION BY object_id ORDER BY primary_id DESC)
In Sqlite I had to come up with this voodoo sub-query to get the same result
SELECT object_id, MAX(_id)
FROM (SELECT object_id, _id
FROM aTable
EXCEPT
SELECT object_id, MAX(_id)
FROM aTable
GROUP BY object_id)
GROUP BY object_id;
Note: The _id is the primary key of aTable and the object table has a 1 to many relationship with the queried table
This might be prohibitively expensive (perhaps only do it when a user inserts a new record?) but how about this:
for user in users:
user-records = select * from records where user=user
if user-records.length > 10:
delete from records where user=user and date<user-records[10]
(in a mix of SQL and pseudocode)
I know this question is old, but the following SQLite statement will do what Rory was originally asking for in one statement - Delete all records for a given UserId that are not the 10 most recent records for that UserId (based on SomeDate).
DELETE FROM data
WHERE AnId IN (SELECT AnId
FROM data AS d
WHERE d.UserId = data.UserId
ORDER BY SomeDate DESC
LIMIT -1 OFFSET 10)
If you already haven't got the answer. If it's one table, then you don't need any joins. You can just use:
Delete From data
where AnId not in (Select AnId
from data
Order by SomeDate DESC
Limit 10)