patternMinor
Select only the last record for multiple values
Viewed 0 times
lasttherecordformultiplevaluesselectonly
Problem
I have a table called "sessions" with say 4 columns like below
How can I get the last
What I need is:
What am trying is this:
but am only getting the finish time for the first name.
MariaDB 10.1.37
id name s_time f_time
01 abc 10.15 10.45
02 abc 11.05 11.55
03 abc 12.18 13.46
04 abc 15.12 16.53
05 def 10.01 12.58
06 def 14.06 16.51
07 def 17.43 18.54
08 xyz 09.45 12.36
09 xyz 14.51 15.57
10 xyz 16.23 18.01
How can I get the last
f_time for each name?What I need is:
name f_time
abc 16.53
def 18.54
xyz 18.01
What am trying is this:
select name,f_time
from sessions
where name in ('abc','def','xyz')
order by id DESC LIMIT 1;but am only getting the finish time for the first name.
MariaDB 10.1.37
Solution
give your example data this should do it.
If you need to pick the
In Postgresql you can use the
i think there's also a way using window functions
SELECT name, max(f_time) AS f_time
FROM sessions
WHERE name IN ('abc','def','xyz')
GROUP BY name
ORDER BY name;If you need to pick the
f_time according to some other column it gets messy.In Postgresql you can use the
distinct on SQL extension.SELECT DISTNICT ON (name)
name, f_time
FROM sessions
WHERE name IN ('abc','def','xyz')
ORDER BY name, id desc;i think there's also a way using window functions
Code Snippets
SELECT name, max(f_time) AS f_time
FROM sessions
WHERE name IN ('abc','def','xyz')
GROUP BY name
ORDER BY name;SELECT DISTNICT ON (name)
name, f_time
FROM sessions
WHERE name IN ('abc','def','xyz')
ORDER BY name, id desc;Context
StackExchange Database Administrators Q#225342, answer score: 5
Revisions (0)
No revisions yet.