My SQL database looks like this
ID DATE
1 2017-01-01
1 2017-01-03
1 2017-01-05
2 2017-01-06
2 2017-01-07
2 2017-01-08
2 2017-01-11
3 2017-01-11
How can I retrieve the Max(DATE) and second latest date for each ID as in below.
ID MAXDATE SECONDMAXDATE
1 2017-01-05 2017-01-03
2 2017-01-11 2017-01-08
3 2017-01-11 2017-01-11 (or 'NONE')
PS: when there is only 1 record, SECONDMAXDATE can display either the MAXDATE or a STRING (eg. NONE)
I think the simplest method is the group_concat()
/substring_index()
"hack":
select id, max(date),
substring_index(substring_index(group_concat(date order by date desc), ',', 2), ',', -1) as second_date
from t
group by id;
Note: This returns the second date as a string rather than a date. You can convert it back to a date if you like.
Also, group_concat()
has a default maximum length of 1,024 bytes. This is sufficient for most purposes (a hundred dates or so). If you have more dates per id, then this mechanism is probably not the best mechanism.