I have a table as follows
ID apiDate totalCases
1 2020-04-18 12:00:00 10
2 2020-04-18 12:00:00 15
3 2020-04-19 12:00:00 20
4 2020-04-19 12:00:00 25
5 2020-04-19 12:00:00 30
6 2020-04-20 12:00:00 35
7 2020-04-20 12:00:00 40
8 2020-04-20 12:00:00 45
I want to return the latest record for each day as follows
ID apiDate totalCases
2 2020-04-18 12:00:00 15
5 2020-04-19 12:00:00 30
8 2020-04-20 12:00:00 45
I have added another column named 'dateonly' and achieved my requirement
SELECT
*
FROM
myTable H
WHERE
`apiDate` =
(
SELECT
max(`apiDate`)
FROM
myTable
WHERE
`dateonly` = H.dateonly
)
I'm looking for a proper solution without adding column 'dateonly'
Your solution using a correlated subquery for filtering is almost there. You just need to fix the correlation clause so it matches on the day rather than on the whole date and time .
I would write this as:
select t.*
from mytable t
where t.apidate = (
select max(t1.apidate)
from mytable t1
where t1.apidate >= date(t.apidate) and t1.apidate < date(t.apidate) + interval 1 day
)
Did you consider window function?
select ID, apiDate, totalCases
from (select t.*,
row_number() over (partition by date(apidate) order by apidate desc) as seqnum
from mytable t
) t
where seqnum = 1;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.