基于另一个表中的值之间的差异删除SQL表中的行

时间:2018-05-28 19:23:56

标签: sql-server date time sql-server-2014 sql-delete

我有一张表(让我们称之为dbo.temp),它有来自不同传感器的逐分钟温度记录:

+-----------+------------+----------+------+
| SENSOR_ID |   DATE     |   TIME   | TEMP |
+-----------+------------+----------+------+
|    106971 | 2017-01-10 | 10:05:00 | 21.1 |
|    106971 | 2017-01-10 | 10:06:00 | 21.1 |
|    106971 | 2017-01-10 | 10:07:00 | 21.2 |
|    106971 | 2017-01-10 | 10:08:00 | 21.1 |
|    106971 | 2017-01-10 | 10:09:00 | 21.1 |
|    106971 | 2017-01-10 | 10:10:00 | 21.2 |
|    106971 | 2017-01-10 | 10:11:00 | 21.2 |
|    106971 | 2017-01-10 | 10:12:00 | 21.2 |
|    106971 | 2017-01-10 | 10:13:00 | 21.3 |
|    106971 | 2017-01-10 | 10:14:00 | 21.4 |
|    106971 | 2017-01-10 | 10:15:00 | 21.4 |
|    106971 | 2017-01-10 | 10:16:00 | 21.4 |
|    106971 | 2017-01-10 | 10:17:00 | 21.5 |
|    106971 | 2017-01-10 | 10:18:00 | 21.3 |
|    106971 | 2017-01-10 | 10:19:00 | 21.3 |
|    106971 | 2017-01-10 | 10:20:00 | 21.3 |
|    106971 | 2017-01-10 | 10:21:00 | 21.4 |
+-----------+------------+----------+------+

第二个(dbo.datetime)包含日期和时间值。

+-------------+-----------+----------+
|    DATE     | TIME_A    | TIME_B  |
+-------------+-----------+----------+
| 2017-01-10  | 10:13:00  | 10:18:00 |
| 2017-01-11  | 09:18:00  | 10:28:00 |
| 2017-01-12  | 10:45:00  | 10:59:00 |
+-------------+-----------+----------+

我想删除dbo.temp中的行,其中时间介于任何给定日期dbo.datetime中给出的两者之间。 SENSOR_ID并不重要,因为TIME_ATIME_B之间的所有数据都需要删除。

例如,我希望dbo.temp在TIME_A上的TIME_B2017-01-10之间删除后成为此内容:

+-----------+------------+----------+------+
| SENSOR_ID |   DATE     |   TIME   | TEMP |
+-----------+------------+----------+------+
|    106971 | 2017-01-10 | 10:05:00 | 21.1 |
|    106971 | 2017-01-10 | 10:06:00 | 21.1 |
|    106971 | 2017-01-10 | 10:07:00 | 21.2 |
|    106971 | 2017-01-10 | 10:08:00 | 21.1 |
|    106971 | 2017-01-10 | 10:09:00 | 21.1 |
|    106971 | 2017-01-10 | 10:10:00 | 21.2 |
|    106971 | 2017-01-10 | 10:11:00 | 21.2 |
|    106971 | 2017-01-10 | 10:12:00 | 21.2 |
|    106971 | 2017-01-10 | 10:19:00 | 21.3 |
|    106971 | 2017-01-10 | 10:20:00 | 21.3 |
|    106971 | 2017-01-10 | 10:21:00 | 21.4 |
+-----------+------------+----------+------+

我该怎么做? dbo.datetime每天TIME_ATIME_B值约为14个月,因此不希望每天手动delete from dbo.temp where date = 'X' and time between 'Y' and 'Z'

1 个答案:

答案 0 :(得分:0)

我不太确定我是否理解您的问题,但您可以尝试此查询

DELETE t
FROM dbo.temp t
JOIN dbo.datetime d ON d.Date = t.Date
WHERE t.Time BETWEEN d.Time_A AND Time_B