我有一个包含大量重复项的数据库,每个重复项都有一个唯一的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
答案 0 :(得分:5)
保持简单。
DELETE FROM tblInvoices
WHERE ID NOT IN
(SELECT MAX(ID)
FROM tblInvoices
GROUP BY EncID, PermitID)
答案 1 :(得分:0)
我能够使用当前的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
答案 2 :(得分:0)
你可以试试这个:
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