How to find most recent date given a set a values that fulfill condition *

StackOverflow https://stackoverflow.com/questions/21861566

  •  13-10-2022
  •  | 
  •  

Domanda

I've been trying to build an sql query that finds from (table) the most recent date for selected id's that fulfill the condition where 'type' is in hierarchy 'vegetables'. My goal is to be able to get the whole row once max(date) and hierarchy conditions are met for each id.

Example values
           ID        DATE         PREFERENCE  AGE
           123       1/3/2013     carrot      14
           123       1/3/2013     apple       12
           123       1/2/2013     carrot      14
           124       1/5/2013     carrot      13
           124       1/3/2013     apple       13
           124       1/2/2013     carrot      14
           125       1/4/2013     carrot      13
           125       1/3/2013     apple       14
           125       1/2/2013     carrot      13

I tried the following

SELECT *
FROM table 
WHERE date in
(SELECT  max(date) FROM (table) WHERE id in (123,124,125))
and preference in 
    (SELECT preference FROM (hierarchy_table) 
                       WHERE hierarchy = vegetables))
                       and id in (123,24,125)

but it doesn't give me the most recent date for each id that meets the hierarchy conditions. (ex. in this scenario I would only get id 124)

Thank you in advance!

È stato utile?

Soluzione 2

I figured this out. Please see the query below as an example:

SELECT * FROM (table) t 
WHERE t.date in 
(SELECT max(date) FROM table sub_t where t.ID = sub_t.ID and (date !> (currentdate))
and preference in
(SELECT preference FROM (hierarchy_table) WHERE hierarchy ='vegetables')
and ID in ('124')

Altri suggerimenti

SELECT  max(date) FROM (table) WHERE id in (123,124,125)

is giving you the max date from all dates, you need to group them. Try replacing with:

SELECT  max(date) FROM (table) GROUP BY id

This way you will get the max date for each id

Change:

max(date) 

To:

-- if your date data is in mm/dd/yyyy
max( str_to_date( date, '%m/%d/%Y' ) )  

OR

-- if your date data is in dd/mm/yyyy
max( str_to_date( date, '%d/%m/%Y' ) )  
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top