我有一张如下表格
CompanyNumber Name Status other column1 other Column2
10 A Active
10 A NULL
11 B Active
11 B NULL
12 C Active
12 C NULL
13 D NULL
14 E Active
...
这样超过30万行。
我想删除状态为NULL的那个,结果表应如下所示:
CompanyNumber Name Status
10 A Active
11 B Active
12 C Active
13 D NULL
14 E Active
答案 0 :(得分:2)
我知道你要删除status为null的行。尝试使用where子句的SQL,如
DELETE
FROM mytable
WHERE status is null
如果您只想删除重复的行,那么您可以执行以下操作:
DELETE
FROM mytable
WHERE status is null
AND CompanyNumber IN (SELECT CompanyNumber
FROM mytable
GROUP BY CompanyNumber
HAVING COUNT(CompanyNumber) > 1)
答案 1 :(得分:2)
;WITH CTE AS
(
SELECT CompanyNumber
,Name
,[Status]
,ROW_NUMBER() OVER (PARTITION BY CompanyNumber, Name ORDER BY [Status] DESC) rn
FROM @TABLE
)
DELETE FROM CTE WHERE rn > 1
答案 2 :(得分:0)
如果您想保留第一条记录并删除其他重复记录,请检查此...
select *,
row_number() over (partition by CompanyNumber order by CompanyNumber)as rno
into #temp from table
delete * from
table
where CompanyNumber in
(select CompanyNumber from #temp where rno != 1)
答案 3 :(得分:0)
您可以在where语句中使用exists子句来查找带有重复项的空行:
delete
from tableA
where tableA.Status is null
and exists (
select *
from tableA t2
where t2.CompanyNumber = tableA.CompanyNumber
and t2.Name = tableA.Name and not t2.Status is null
)