我正尝试使用cte从与外科医生名称'Lucille Torres'相关的表'exchange_transactions'中删除重复的行。 transaction_id列应该是唯一的,但是在这种情况下是重复的,因此尝试删除它们。我尝试了这段代码,但似乎没有用。将“ DELETE”替换为“ SELECT *”会显示我要删除的所有行。我在做什么错了?
WITH cte AS (
SELECT
transaction_id,
surgeon,
ROW_NUMBER() OVER (
PARTITION BY
transaction_id
) row_num
FROM exchange_transactions)
DELETE FROM cte
WHERE surgeon = 'Lucille Torres' AND row_num > 1
答案 0 :(得分:0)
使用ROWID
列获取每个不会删除的transaction_id
的最小值:
delete from exchange_transactions
where surgeon = 'Lucille Torres'
and exists (
select 1 from exchange_transactions t
where t.surgeon = exchange_transactions.surgeon
and t.transaction_id = exchange_transactions.transaction_id
and t.rowid < exchange_transactions.rowid
)
答案 1 :(得分:0)
直接从CTE删除在SqLite中不起作用。
但是如果该表具有主键(例如id
)
那么CTE的结果可用于删除。
例如:
WITH CTE_DUPS AS
(
SELECT id,
ROW_NUMBER() OVER (
PARTITION BY surgeon, transaction_id
ORDER BY id) AS rn
FROM exchange_transactions
WHERE surgeon = 'Lucille Torres'
)
DELETE
FROM exchange_transactions
WHERE id IN (select id from CTE_DUPS where rn > 1)
在 db <>小提琴here
上进行测试