1

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'

GMB
  • 216,147
  • 25
  • 84
  • 135
troshan
  • 134
  • 1
  • 11

2 Answers2

1

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
)
GMB
  • 216,147
  • 25
  • 84
  • 135
0

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;
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786