简体   繁体   中英

Select the latest year in a column using SQL query

I have a dataframe like this

Value. Date
A 08/08/2009
A 09/12/2021
A 05/10/2022
A 06/09/2022
A 07/08/2022

I need output like

VALUE DATE
A 05/10/2022
A 06/09/2022
A 07/08/2022

We have to print a latest year with all month data present in the date column.please refer output table.

i used SQL query like

Select Top 10 * from table where Order by (Date) DESC;

The max() select only one date so that didn't help me

But didn't get expected answer. Can please someone help me with the query?

You can just use MAX in a subquery, this will produce the intended outcome you have shown in your question:

SELECT yourcolumn
FROM yourtable
WHERE 
YEAR(yourcolumn) = (SELECT MAX(YEAR(yourcolumn)) FROM yourtable);

The latest year is 2022, so MAX in the subquery will find this year and the whole query will select all dates in 2022.

SELECT *
FROM tablename
WHERE datecolumn >= (SELECT DATE_FORMAT(MAX(datecolumn), '%Y-01-01')
                     FROM tablename)

To improve this query you'd have an index by datecolumn (or where this column is an expression prefix).

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