简体   繁体   English

不带分组依据的SQL max

[英]SQL max without group by

I would like to get one row with the maximum date. 我想获得最长日期的一行。 I cannot use group by as I need to retrieve all data in that row. 我无法使用分组依据,因为我需要检索该行中的所有数据。

I have this: 我有这个:

ID     Date          Country
1      05/05/2019    US
2      05/06/2019    UK

I want to get this: 我想得到这个:

ID     Date          Country
2      05/06/2019    UK

I've tried the below but it didn't work for me 我尝试了以下内容,但对我不起作用

select TOP 1 ID, Date, country
from table
order by Date desc

I don't believe you. 我不相信你 Here is a db<>fiddle that shows three different interpretations of the date in your sample data: 是一个db <>小提琴,它显示了示例数据中日期的三种不同解释:

  • as a string 作为一个字符串
  • as mm/dd/yyyy 以mm / dd / yyyy
  • as dd/mm/yyyy 为dd / mm / yyyy

All three of them produce the same result. 他们三个都产生相同的结果。

I suspect that your actual data is more complicated and you have oversimplified the example for the question. 我怀疑您的实际数据更加复杂,并且您简化了该问题的示例。 Further, my suspicion is that the date column is stored as a string rather than a date . 此外,我怀疑date列存储为字符串而不是date

As a string, you might have some hidden characters that affect the sorting (such as leading spaces). 作为字符串,您可能会有一些影响排序的隐藏字符(例如前导空格)。

If this is the case, fix the data type and your code will work. 在这种情况下,请修复数据类型,您的代码将可以使用。

你可以试试这个吗?

select Top 1 ID,Date, country from table where date = max(date)

This depends on what DB system you are using. 这取决于您所使用的数据库系统。

In Microsoft SQL server, you can use row_number() function: 在Microsoft SQL Server中,可以使用row_number()函数:

select top 1 *
from facts
order by ROW_NUMBER() over (order by dateKey)

首先在[Date]列中设置DATE or DATETIME数据类型,然后尝试以下代码:

SELECT TOP 1 ID, [Date] , country FROM TableName ORDER BY Date DESC

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

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