读取测量设备的所有最新测量值

问题描述 投票:0回答:5

我有一个看起来像这样的表:

id | date             | device_id | measurement_id | value
---+------------------+-----------+----------------+------
1  | 2020-02-24 20:00 | 3         | 1              | 7.9
2  | 2020-02-24 20:00 | 3         | 2              | 3.2
3  | 2020-02-24 20:00 | 3         | 3              | 5.12
4  | 2020-02-24 20:00 | 1         | 1              | 7.9
5  | 2020-02-24 20:00 | 1         | 2              | 3.2
6  | 2020-02-24 20:00 | 1         | 3              | 5.12
7  | 2020-02-24 20:10 | 1         | 1              | 15.2
8  | 2020-02-24 20:10 | 1         | 2              | 5.8
9  | 2020-02-24 20:10 | 1         | 3              | 9.1
10 | 2020-02-24 20:10 | 2         | 1              | 4.6
11 | 2020-02-24 20:10 | 2         | 2              | 2.3
12 | 2020-02-24 20:20 | 1         | 4              | 45.1

现在,我想根据device_id读取每个measurement_id的最新值。因此,在此示例中(对于device_id 1):

id | date             | device_id | measurement_id | value
---+------------------+-----------+----------------+------
7  | 2020-02-24 20:10 | 1         | 1              | 15.2
8  | 2020-02-24 20:10 | 1         | 2              | 5.8
9  | 2020-02-24 20:10 | 1         | 3              | 9.1
12 | 2020-02-24 20:20 | 1         | 4              | 45.1

如何在Azure SQL Server上使用T-SQL最好地实现这一点?

sql tsql azure-sql-database
5个回答
1
投票

使用正确的索引,相关子查询通常具有最佳性能:

select t.*
from t
where t.device = 1 and
      t.date = (select max(t2.date) 
                from t t2 
                where t2.device_id = t.device_id and
                      t2.measurement_id = t.measurement_id
               );

您想要的索引在(device_id, measurement_id, date)上。

规范解决方案使用row_number(),并且效果也差不多。


1
投票

尝试一下,没有测试...

select * 
from my_table mt1 
where mt1.date = (select max(mt2.date) 
                   from my_table mt2 
                   where mt2.device_id = mt1.device_id 
                   and  mt2.measurement_id = mt1.measurement_id
                   )

0
投票

您可以使用row_number函数获取每个设备ID和测量ID的最新记录:

select a.*
from
(select *,
       row_number() over(partition by device_id,measurement_id order by date desc) as rownum
from table) a
where a.rownum=1

0
投票

非常简单。您将要同时使用MAX语句和GroupBy子句。试试看,如果您需要更多具体示例,我可以为您提供帮助。

-Matt-


0
投票

请在下面运行此代码,我已经测试过并且可以正常工作,过滤device_id=1

select * from dbo.test11 where value IN (
    select Max(value) FROM 
            (select * from test11 where device_id=1) tb2  group by tb2.measurement_id
        )

创建表包含与您相同的数据:

enter image description here

执行查询并获得结果:

enter image description here

希望这会有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.