从SQL获取最新数据

时间:2018-01-11 23:48:14

标签: sql

我有一个问题Simmilar to this one,除了我有一个看起来像这样的表:

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 

2 个答案:

答案 0 :(得分:1)

(根据您的数据库,您可能需要稍微更改一下语法。)

这个适用于SQLite3:

select Building_ID,Sector_ID,Temperature,Temp_Date
  from t
  group by Building_ID,Sector_ID having max(Temp_Date);

对于使用having语法更严格的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)

答案 1 :(得分:0)

在大多数数据库中,您将使用ANSI标准窗口函数row_number()

select t.*
from (select t.*,
             row_number() over (partition by building_id, sector_id order by temp_date desc) as seqnum
      from mytable t
     ) t
where seqnum = 1;