简体   繁体   English

SQL查询:从查询结果中排除部分重复

[英]SQL query: Exclude partial duplicates from query result

I have data from multiple sensors. 我有来自多个传感器的数据。 Each record has own id, sensor id, timestamp and measured value. 每个记录都有自己的ID,传感器ID,时间戳和测量值。 Like this: 像这样:

|--id--|--id_sensor--|-------timestamp-------|--value--|
    1          1       '2017-08-23 10:00:00'     30
    2          1       '2017-08-23 10:02:00'     30
    3          1       '2017-08-23 10:04:00'     31
    4          1       '2017-08-23 10:06:00'     31
    5          1       '2017-08-23 10:08:00'     32
    6          2       '2017-08-23 10:00:00'     24
    7          2       '2017-08-23 10:01:00'     24
    8          2       '2017-08-23 10:02:00'     24
    9          2       '2017-08-23 10:03:00'     24
    10         2       '2017-08-23 10:04:00'     24
    11         2       '2017-08-23 10:05:00'     24
    12         2       '2017-08-23 10:06:00'     25

I would like to exclude record if the value did not change so the result should look like this: 如果值未更改,我想排除记录,因此结果应如下所示:

|--id--|--id_sensor--|-------timestamp-------|--value--|
    1          1       '2017-08-23 10:00:00'     30
    3          1       '2017-08-23 10:04:00'     31
    5          1       '2017-08-23 10:08:00'     32
    6          2       '2017-08-23 10:00:00'     24
    12         2       '2017-08-23 10:06:00'     25

I have to be compatible with sql server 2000 :-( I would like to avoid using cursors if posible. Can anybody help? 我必须与sql server 2000兼容:-(如果可能,我想避免使用游标。有人可以帮忙吗?

Something like: 就像是:

select your_table.* from your_table
join(
    select min(id) as mid from your_table group by value
) t
on your_table.id = t.mid

I think the following may be closer to what you really want: 我认为以下内容可能更接近您真正想要的:

select t.*
from (select t.*,
             (select top 1 t2.value
              from t t2
              where t2.sensor = t.sensor and
                    t2.timestamp < t.timestamp
              order by t2.timestamp desc
             ) as prev_value
      from t
     ) t
where prev_value is null or prev_value <> value;

You really should upgrade to a supported version of SQL Server. 您确实应该升级到受支持的SQL Server版本。 Free versions are even available. 免费版本甚至可用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM