从SQL获取的最新数据
我有一个问题,除了我有一张表,看起来像这样:从SQL获取的最新数据,sql,Sql,我有一个问题,除了我有一张表,看起来像这样: Temp_Date Building_ID Sector_ID Temperature [Date/Time] [I32] [I32] [DBL] 1/9/2018 4:14:31 AM 456 0 20.23 1/9/2018
Temp_Date Building_ID Sector_ID Temperature
[Date/Time] [I32] [I32] [DBL]
1/9/2018 4:14:31 AM 456 0 20.23
1/9/2018 4:15:14 AM 123 1 35.23
1/9/2018 4:16:21 AM 123 0 15.23
1/9/2018 4:15:45 AM 123 2 25.23
1/9/2018 4:16:21 AM 456 0 25.23
1/9/2018 4:16:59 AM 123 1 35.23
我想获得每个独特建筑/地段组合的最新记录温度的结果数据
对于示例数据集,我要查找的表如下所示
Building_ID Sector_ID Temperature
123 0 15.23
123 1 35.23
123 2 25.23
456 0 25.23
据我所知,代码应该如下所示:
select t.Building_ID, t.Sector_ID, t.Temperature, t.Temp_Date
from MyTable t
inner join (
select Building_ID, Sector_ID, max(Temp_Date) as MaxTemp_Date
from MyTable
group by Building_ID
) tm on t.Building_ID = tm.Building_ID and t.Sector_ID = tm.Sector_ID and t.Temp_Date = tm.Temp_Date
编辑
今天早上我又回来了,我相信下面的代码能满足我的需求
select t.Building_ID, t.Sector_ID, t.Temperature, t.Temp_Date
from MyTable t
inner join (
select Building_ID, Sector_ID, max(date_time) as maxMaxTemp_Date
from MyTable t
group by Building_ID, Sector_ID
) tm on t.Building_ID = tm.Building_ID and t.Sector_ID = tm.Sector_ID and t.Temp_Date=tm.MaxTemp_Date
ORDER BY t.Building_ID, t.Sector_ID
在大多数数据库中,您将使用ANSI标准窗口函数row_number:
根据您的数据库,您可能需要稍微更改语法 这一个适用于SQLite3:
select Building_ID,Sector_ID,Temperature,Temp_Date
from t
group by Building_ID,Sector_ID having max(Temp_Date);
对于语法更严格的MySQL、SQL Server和PostgreSQL,如下所示:
select Building_ID,Sector_ID,(
select Temperature
from t
where a.Building_ID = t.Building_ID
and a.Sector_ID = t.Sector_ID
and max(a.Temp_Date) = t.Temp_Date) Temperature
from t a
group by Building_ID,Sector_ID
having max(Temp_Date) = max(Temp_Date)
用您正在使用的数据库标记您的问题。您应该提供的第一个信息是您正在使用的dbms。您在内部查询的group by子句中缺少Section_ID。@kc2018这是我的问题如果您给出完整答案,我将接受它作为solution@ATE-恩格,你明白了!虽然我想要的是最新的温度值而不是最高温度,但它不应该有maxt.Temp_Date吗?
select Building_ID,Sector_ID,(
select Temperature
from t
where a.Building_ID = t.Building_ID
and a.Sector_ID = t.Sector_ID
and max(a.Temp_Date) = t.Temp_Date) Temperature
from t a
group by Building_ID,Sector_ID
having max(Temp_Date) = max(Temp_Date)