簡體   English   中英

SQL查詢:從查詢結果中排除部分重復

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

我有來自多個傳感器的數據。 每個記錄都有自己的ID,傳感器ID,時間戳和測量值。 像這樣:

|--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

如果值未更改,我想排除記錄,因此結果應如下所示:

|--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

我必須與sql server 2000兼容:-(如果可能,我想避免使用游標。有人可以幫忙嗎?

就像是:

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

我認為以下內容可能更接近您真正想要的:

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;

您確實應該升級到受支持的SQL Server版本。 免費版本甚至可用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM