Home > Mobile >  I am working on a SQL query to filter the category based on the oldest datetime of its respective fr
I am working on a SQL query to filter the category based on the oldest datetime of its respective fr

Time:10-06

Food category Datetime
Apple morning 2021-10-06 00:00:00
Apple Afternoon 2021-10-06 01:00:00
Apple Night 2021-10-06 02:00:00
Dates Brunch 2021-10-06 10:00:00
Dates Snack 2021-10-06 17:00:00

CodePudding user response:

Is this you want :

select t.*
from(select t.*, row_number() over (partition by food order by datetime) as seq
     from table t
     ) t
where seq = 1;

CodePudding user response:

There are many ways to achieve this results

Here is the firs one that came to mind for me:

SELECT 
    Food
FROM 
    myTable
GROUP BY 
    Food
HAVING MIN(DateTime)

This uses and aggregate function in the HAVING clause to find the MIN(aka oldest) datetime

  •  Tags:  
  • sql
  • Related