Select newest datetime for each userid MS Sql Server
I have a table used for a chat. Among others there is a field called userid and a field called timesent. I need to know the latest timesent for each userid in the table, so that I can delete them from the table if they haven't said anything for 3 minutes, in which case I will assume they are gone.
I can't really crack this nut... How do I query.
I could of course split it up and first select all the userids and then loop through them and select top 1 timesent in my method, but I was wondering if sql alon开发者_运维百科e can do the trick, so I don't need to execute tons of queries.
To get the latest timesent
per userid
you can use MAX
SELECT userid, MAX(timesent) AS timesent
FROM your_table
GROUP BY userid
Or to do the specified delete
you can use
DELETE your_table
FROM your_table y1
WHERE NOT EXISTS(SELECT *
FROM your_table y2
WHERE y2.userid = y1.userid
AND y2.timesent >= DATEADD(MINUTE, -3, GETDATE()))
精彩评论