如果Mssql中两列数据相同,需要删除数据库中的所有重复行
Need to delete all duplicate row in database if two column data are same in Mssql
嗨,我有一个 table 像这样的命名积分
ID identity
Name varchar
CustCode varchar
ConsignorNo varchar
Address varchar
但是我在整个数据库中有这样的重复行
ID 1 Name John CustCode A1 ConsignorNo BBS Address XXX
ID 2 Name Mari CustCode A2 ConsignorNo NRM Address XXX
ID 3 Name John CustCode A1 ConsignorNo BBS Address XXX
ID 4 Name Mari CustCode A2 ConsignorNo MMS Address XXX
由于John的CustCode和ConsignorNo相同,所以必须删除,Mari不应该删除,因为它包含相同的custcode但不同的ConsignorNo。我试过这个但抛出事务日志已满的错误。查询是
delete from Credits
where ID not in (select MAX(ID)
from Credits
group by ConsignerNo, CustomerCode)
一种方法,使用 CTE
+ ROW_NUMBER
:
WITH CTE AS
(
SELECT t.*,
RN = ROW_NUMBER() OVER (PARTITION BY Custcode, ConsignorNo ORDER BY ID DESC)
FROM dbo.tableName
)
DELETE FROM CTE
WHERE RN > 1
我喜欢它,因为它很简单,可以轻松更改以查看要删除的内容。
以上删除了除一行(具有最高 ID 的行)以外的所有行。如果你想删除所有重复的(不是很清楚)那么你可以使用 COUNT(*)OVER(PARTITION BY Custcode, ConsignorNo)
:
WITH CTE AS
(
SELECT t.*,
Count = COUNT(*) OVER (PARTITION BY Custcode, ConsignorNo)
FROM dbo.tableName
)
DELETE FROM CTE
WHERE Count > 1
尝试这样的事情:
delete from Credits
where ID = (select MAX(ID)
from Credits
group by ConsignerNo, CustomerCode having count(*)>1)
嗨,我有一个 table 像这样的命名积分
ID identity
Name varchar
CustCode varchar
ConsignorNo varchar
Address varchar
但是我在整个数据库中有这样的重复行
ID 1 Name John CustCode A1 ConsignorNo BBS Address XXX
ID 2 Name Mari CustCode A2 ConsignorNo NRM Address XXX
ID 3 Name John CustCode A1 ConsignorNo BBS Address XXX
ID 4 Name Mari CustCode A2 ConsignorNo MMS Address XXX
由于John的CustCode和ConsignorNo相同,所以必须删除,Mari不应该删除,因为它包含相同的custcode但不同的ConsignorNo。我试过这个但抛出事务日志已满的错误。查询是
delete from Credits
where ID not in (select MAX(ID)
from Credits
group by ConsignerNo, CustomerCode)
一种方法,使用 CTE
+ ROW_NUMBER
:
WITH CTE AS
(
SELECT t.*,
RN = ROW_NUMBER() OVER (PARTITION BY Custcode, ConsignorNo ORDER BY ID DESC)
FROM dbo.tableName
)
DELETE FROM CTE
WHERE RN > 1
我喜欢它,因为它很简单,可以轻松更改以查看要删除的内容。
以上删除了除一行(具有最高 ID 的行)以外的所有行。如果你想删除所有重复的(不是很清楚)那么你可以使用 COUNT(*)OVER(PARTITION BY Custcode, ConsignorNo)
:
WITH CTE AS
(
SELECT t.*,
Count = COUNT(*) OVER (PARTITION BY Custcode, ConsignorNo)
FROM dbo.tableName
)
DELETE FROM CTE
WHERE Count > 1
尝试这样的事情:
delete from Credits
where ID = (select MAX(ID)
from Credits
group by ConsignerNo, CustomerCode having count(*)>1)