Deleting record in SQL depending on next record(根据下一条记录删除SQL中的记录)
问题描述
我有以下列的记录:ID、Time_End 和 Attribute.
I have records with columns: ID, Time_End and Attribute.
我需要删除所有记录,
WHERE Time_End = '1990-01-01 00:00:00.000' AND Attribute <> '9'
但仅限:
- 如果下一行没有相同的属性编号
或
- 下一行具有相同的属性编号和
Time_End值1990-01-01 00:00:00.000
例如:
ID Time_End Attribute
---------------------------------------------
235 1990-01-01 00:00:00.000 5 /delete
236 1990-01-01 00:00:00.000 5 /delete
237 1990-01-01 00:00:00.000 5
238 2016-10-10 23:45:40.000 5
ID Time_End Attribute
---------------------------------------------
312 1990-01-01 00:00:00.000 8 /delete
313 2016-01-09 18:00:00.000 6
314 1990-01-01 00:00:00.000 4 /delete
315 1990-01-01 00:00:00.000 7
316 2016-10-10 23:45:40.000 7
我们的客户有 50 个数据库表,每个表中有数千条记录(当然还有更多的列,我只提到了那些对解决方案有影响的列).记录从PLC发送到数据库,但有时(我们不知道为什么)PLC也会发送错误的记录.
Our customer have 50 database tables with thousands of records in every table (and of course more columns, I mentioned only those, which have impact on solution). Records are send in to the database from PLC, but sometimes (we don't know why) PLC send also wrong records.
所以我需要一个查询来查找那些错误的记录并删除它们.:)
So what I need is a query which finds those wrong records and deletes them. :)
有人知道 SQL 代码应该是什么样的吗?
Anybody who knows how the SQL code should look like?
推荐答案
请看下面我的 SQL.首先,我们使用两个窗口函数 (LEAD) 收集要删除的 id,以获取下一行所需的数据.然后,计算所有需要的数据后,应用 OP 提出的评估规则.最后,使用获取到的 id 通过带有 in 子句的 id 删除 tablet 受影响的记录.
Please see my SQL below. First, we collect ids to delete using two window functions (LEAD) to get the next row needed data. Then, with all needed data computed, apply the evaluation rules proposed by the OP. Last, use the obtained ids to delete the affected records of the tablet by id with an in clause.
DELETE toDeleteTable
WHERE toDeleteTable.id IN (WITH dataSet
AS (SELECT toDeleteTable.id,
toDeleteTable.time_end,
toDeleteTable.attribute,
LEAD(toDeleteTable.time_end,1,0) OVER (ORDER BY toDeleteTable.id) AS next_time_end,
LEAD(toDeleteTable.attribute,1,0) OVER (ORDER BY toDeleteTable.id) AS next_attribute
FROM toDeleteTable)
SELECT dataSet.id
FROM dataSet
WHERE dataSet.time_end = '1990-01-01 00:00:00.000'
AND dataSet.attribute <> '9'
AND ( (dataSet.next_attribute = dataSet.attribute AND dataSet.next_time_end = '1990-01-01 00:00:00.000')
OR dataSet.next_attribute <> dataSet.attribute)
)
这篇关于根据下一条记录删除SQL中的记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:根据下一条记录删除SQL中的记录
基础教程推荐
- 从字符串 TSQL 中获取数字 2021-01-01
- CHECKSUM 和 CHECKSUM_AGG:算法是什么? 2021-01-01
- 使用 VBS 和注册表来确定安装了哪个版本和 32 位 2021-01-01
- 带更新的 sqlite CTE 2022-01-01
- while 在触发器内循环以遍历 sql 中表的所有列 2022-01-01
- ORA-01830:日期格式图片在转换整个输入字符串之前结束/选择日期查询的总和 2021-01-01
- MySQL 5.7参照时间戳生成日期列 2022-01-01
- MySQL根据从其他列分组的值,对两列之间的值进行求和 2022-01-01
- 带有WHERE子句的LAG()函数 2022-01-01
- 如何在 CakePHP 3 中实现 INSERT ON DUPLICATE KEY UPDATE aka upsert? 2021-01-01
