简体   繁体   中英

Select value where max(date)

I have a dataset with several values for the same medical procedure. I want to select the value where date_ref is max but I am not getting how to do that. Below it is an example of the dataset

PROC_CODE | VALUE | DATE
123456      20.90  2020-01-01
123456      30.00  2021-01-01
123456      15.47  2022-06-01

I want to return only the last row of the dataset, which assigns VALUE for the most recent date

PROC_CODE | VALUE | DATE
123456      15.47  2022-06-01

I tried the following code but it returns an error. What I am missing in my logic?

SELECT 
PROC_CODE, VALUE
FROM MY_TABLE
WHERE MAX(DATE)
GROUP BY PROC_CODE -- Only grouping by PROC_CODE because grouping by PROC_CODE and VALUE returns the 3 lines of the dataset

You can use a subquery in your WHERE clause to do this:

SELECT PROC_CODE, VALUE, DATE
FROM MY_TABLE
WHERE DATE = (SELECT MAX(DATE) FROM MY_TABLE);

If you are wanting the value for the max date for each proc_code, then a correlated subquery will work as well:

SELECT PROC_CODE, VALUE, DATE
FROM MY_TABLE as MT
WHERE DATE = (SELECT MAX(DATE) FROM MY_TABLE WHERE PROC_CODE = MT.PROC_CODE);

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM