简体   繁体   English

Select 使用 SQL 查询的列中的最新年份

[英]Select the latest year in a column using SQL query

I have a dataframe like this我有一个这样的 dataframe

Value.价值。 Date日期
A一种 08/08/2009 08/08/2009
A一种 09/12/2021 2021 年 9 月 12 日
A一种 05/10/2022 05/10/2022
A一种 06/09/2022 06/09/2022
A一种 07/08/2022 07/08/2022

I need output like我需要 output 喜欢

VALUE价值 DATE日期
A一种 05/10/2022 05/10/2022
A一种 06/09/2022 06/09/2022
A一种 07/08/2022 07/08/2022

We have to print a latest year with all month data present in the date column.please refer output table.我们必须打印日期列中所有月份数据的最新年份。请参考 output 表。

i used SQL query like我使用了 SQL 查询

Select Top 10 * from table where Order by (Date) DESC; Select 前 10 * 来自按(日期)DESC 排序的表;

The max() select only one date so that didn't help me max() select 只有一个日期所以对我没有帮助

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:您可以在子查询中使用MAX ,这将产生您在问题中显示的预期结果:

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.最近的年份是 2022 年,因此子查询中的MAX将找到今年,整个查询将 select 所有日期都在 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).要改进此查询,您需要按datecolumn列(或此列是表达式前缀的位置)建立索引。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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