Search code examples
sqlgreatest-n-per-group

How to get the max ID for every Type every Date


I want to keep the highest report id (Report_ID) for every type (Types) for every single date (Date)

Note: The data column has multiple dates, only 01.01.2021 is shown below.

  SELECT a.*
  FROM Table1 a
  JOIN (
    SELECT Date, MAX(Report_ID) as maxID
    FROM Table1
    GROUP BY Date) b 
  ON a.Report_ID = b.maxID
  WHERE a.Date = '2021-01-01'
  ORDER BY Date desc

enter image description here


Solution

  • You can use a correlated subquery:

    select t.*
    from t
    where t.report_id = (select max(t2.report_id)
                         from t t2
                         where t2.date = t.date and t2.type = t.type
                        );