删除多个重复项,在 sql 中留下最大 ID
Delete multiple duplicates leaving max id in sql
我有一个包含大量重复项的数据库,每个重复项都有一个唯一的 ID
,但它们的 PermitID
和 EncID
是相同的。我需要删除数据库中除最高 ID 以外的所有 ID。
sql语句,
DELETE FROM tblInvoices
WHERE EncID = '0237' AND PermitID IN (
SELECT Max(ID) FROM tblInvoices Group BY PermitID)
删除所有记录。我试过了
DELETE FROM tblInvoices
WHERE EncID = '0237' AND PermitID
< (SELECT Max(ID) FROM tblInvoices Group BY PermitID)
但我收到错误
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
数据示例为
ID PermitID EncID
1 11 22
2 11 22
3 11 22
4 12 23
5 12 23
我想保留 3,删除 2 和 1。我还想保留 5,删除 4
我能够使用当前的 SQL 声明
WITH CTE AS
(
SELECT ROW_NUMBER() OVER (Partition BY PermitID ORDER BY ID) AS RowNumber, *
FROM tblInvoices
WHERE EncID = '0237'
)
DELETE FROM CTE
WHERE RowNumber < 13
你可以试试这个:
WITH cte AS
(
SELECT row_number() OVER (PARTITION by permitid ORDER BY Id DESC) r,ID,permitid,encid
FROM tblinvoices
)
DELETE FROM cte WHERE r > 1
保持简单。
DELETE FROM tblInvoices
WHERE ID NOT IN
(SELECT MAX(ID)
FROM tblInvoices
GROUP BY EncID, PermitID)
我有一个包含大量重复项的数据库,每个重复项都有一个唯一的 ID
,但它们的 PermitID
和 EncID
是相同的。我需要删除数据库中除最高 ID 以外的所有 ID。
sql语句,
DELETE FROM tblInvoices
WHERE EncID = '0237' AND PermitID IN (
SELECT Max(ID) FROM tblInvoices Group BY PermitID)
删除所有记录。我试过了
DELETE FROM tblInvoices
WHERE EncID = '0237' AND PermitID
< (SELECT Max(ID) FROM tblInvoices Group BY PermitID)
但我收到错误
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
数据示例为
ID PermitID EncID
1 11 22
2 11 22
3 11 22
4 12 23
5 12 23
我想保留 3,删除 2 和 1。我还想保留 5,删除 4
我能够使用当前的 SQL 声明
WITH CTE AS
(
SELECT ROW_NUMBER() OVER (Partition BY PermitID ORDER BY ID) AS RowNumber, *
FROM tblInvoices
WHERE EncID = '0237'
)
DELETE FROM CTE
WHERE RowNumber < 13
你可以试试这个:
WITH cte AS
(
SELECT row_number() OVER (PARTITION by permitid ORDER BY Id DESC) r,ID,permitid,encid
FROM tblinvoices
)
DELETE FROM cte WHERE r > 1
保持简单。
DELETE FROM tblInvoices
WHERE ID NOT IN
(SELECT MAX(ID)
FROM tblInvoices
GROUP BY EncID, PermitID)