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 服务器 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 服务器版本。甚至提供免费版本。
我有来自多个传感器的数据。每条记录都有自己的 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 服务器 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 服务器版本。甚至提供免费版本。