我有一张桌子,有
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)
但是它只给我返回第一行。
表也将具有连续日期,例如
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)
如果您的dbms支持,则可以使用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 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 location, MAX(Date)
FROM foo
GROUP BY location
应该给您您想要的,但是如果isBlocked具有不同的值,则不添加isBlocked,因为那样您将需要将它添加到group by语句中,这将使其更多行。
select *
from locations_table t
where t.col_date = (select max(col_date)
from locations_table)