获取 table 中的最大日期时间,每个日期有多个条目

Get the max date time in a table with multiple entries for each date

我有一个 table

Location | IsBroken | Date
AZ          1         2019-01-01 12:00
CA          0         2019-01-01 12:00
NY          1         2019-01-01 12:00
AZ          1         2019-01-01 15:00
CA          0         2019-01-01 15:00
NY          1         2019-01-01 15:00
AZ          1         2019-01-01 19:00
CA          0         2019-01-01 19:00
NY          1         2019-01-01 19:00
AZ          1         2019-01-02 14:00
CA          0         2019-01-02 14:00
NY          1         2019-01-02 14:00
AZ          1         2019-01-02 16:00
CA          0         2019-01-02 16:00
NY          1         2019-01-02 16:00
AZ          1         2019-01-03 12:00
CA          0         2019-01-03 12:00
NY          1         2019-01-03 12:00
AZ          1         2019-01-03 17:00
CA          0         2019-01-03 17:00
NY          1         2019-01-03 17:00

而且我每个日期只需要一行,最好是最大值,所以结果应该是

AZ          1         2019-01-01 19:00
CA          0         2019-01-01 19:00
NY          1         2019-01-01 19:00
AZ          1         2019-01-02 16:00
CA          0         2019-01-02 16:00
NY          1         2019-01-02 16:00
AZ          1         2019-01-03 17:00
CA          0         2019-01-03 17:00
NY          1         2019-01-03 17:00

我试过在以下位置使用嵌套查询:

WHERE foo.Date = (SELECT MAX(Date) FROM foo)

但它只返回 1 行。

table 也会有连续的日期,比如

2019-01-02 
2019-01-03

等等

我需要每个日期的结果。

使用相关子查询

select t1.* from table_name t1
where t1.date= ( select max(date) from table_name t2 where t1.location=te.location and t1.date=t2.date)

如果您的数据库支持

,您可以使用 row_number()
select * from (select *,row_number()over(partition by location,Date order by date desc) rn
from table_name
) a where a.rn=1
SELECT location, MAX(Date) 
FROM foo
GROUP BY location

我认为应该给你你想要的,但是 w/o 如果它有不同的值,则 isBlocked,因为那样你将需要将它添加到 group by 语句中,这将使它更多行。

不存在:

select t.* from tablename t
where not exists (
  select 1 from tablename
  where [Location] = t.[Location] 
    and convert(date, [Date]) = convert(date, t.[Date])
    and [Date] > t.[Date]
)

参见demo
结果:

> Location | IsBroken | Date               
> :------- | -------: | :------------------
> AZ       |        1 | 01/01/2019 19:00:00
> CA       |        0 | 01/01/2019 19:00:00
> NY       |        1 | 01/01/2019 19:00:00
> AZ       |        1 | 02/01/2019 16:00:00
> CA       |        0 | 02/01/2019 16:00:00
> NY       |        1 | 02/01/2019 16:00:00
> AZ       |        1 | 03/01/2019 17:00:00
> CA       |        0 | 03/01/2019 17:00:00
> NY       |        1 | 03/01/2019 17:00:00
select * 
from locations_table t
where t.col_date = (select max(col_date)
                    from locations_table)

dbfiddle