SQL Server - 删除重复项

时间:2014-08-06 11:58:23

标签: sql sql-server

这是我的表格。我想删除具有相应“已删除”状态的记录。请参阅输出示例:

ID-------VisitDate---------Name-----Status
abc123 - 2014-08-01 10:30  -john   -null
abc123 - 2014-08-01 10:35 - john- deleted
abc123 - 2014-08-02 12:30 - john - null

yyz999 - 2014-08-02 08:30 - Tom - null
xyz999 - 2014-08-01 08:31 - Tom- deleted
xyz999 - 2014-08-02 12:30 - Tom - null
pqr879 - 2014-08-05 11:10  - Anny - null

预期产出:

ID-------VisitDate---------Name-----Status
abc123 - 2014-08-02 12:30 - john - null
xyz999 - 2014-08-02 12:30 - Tom - null
pqr879 - 2014-08-05 11:10  - Anny - null

5 个答案:

答案 0 :(得分:0)

请尝试使用CTE:

with c as
(
    select 
        *, 
        row_number() over(partition by id order by Status) as n
    from tbl
)
delete from c
where n > 1;

答案 1 :(得分:0)

我想你要保留自上次deleted以来的所有记录。如果是这样的话:

with todelete as (
      select t.*,
             max(case when status = 'deleted' then VisitDate end) over
                 (partition by id) as DeletedVisitDate
      from table t
     )
delete from todelete
    where VisitDate <= DeletedVisitDate;

如果您只想查询以获取这些记录:

with t as (
      select t.*,
             max(case when status = 'deleted' then VisitDate end) over
                 (partition by id) as DeletedVisitDate
      from table t
     )
select *
from todelete
where VisitDate > DeletedVisitDate or DeletedVisitDate is null;

答案 2 :(得分:0)

要删除状态已删除的记录,请使用以下命令:

DELETE FROM TableName WHERE status = 'deleted'

此外,您的预期输出看起来只需要显示最大访问日期,因此您可以在运行DELETE后使用以下SELECT查询。

SELECT ID, MAX(VisitDate) AS VisitDate, Name, Status 
FROM TableName 
GROUP BY ID, Name, Status

答案 3 :(得分:0)

DECLARE @T TABLE (ID VARCHAR(10),VisitDate DATE, Name VARCHAR(10),Status VARCHAR(10) )
INSERT INTO @T (ID,VisitDate,Name,Status)VALUES('abc123','2014-08-01','john',NULL)
INSERT INTO @T (ID,VisitDate,Name,Status)VALUES('abc123','2014-08-02','john','deleted')
INSERT INTO @T (ID,VisitDate,Name,Status)VALUES('abc123','2014-08-03','john',NULL)
INSERT INTO @T (ID,VisitDate,Name,Status)VALUES('yyz999','2014-06-04','Tom',NULL)
INSERT INTO @T (ID,VisitDate,Name,Status)VALUES('yyz999','2014-06-02','Tom','deleted')
INSERT INTO @T (ID,VisitDate,Name,Status)VALUES('pqr879','2014-07-01','Anny',NULL)
INSERT INTO @T (ID,VisitDate,Name,Status)VALUES('pqr879','2014-07-01','Anny',NULL)
INSERT INTO @T (ID,VisitDate,Name,Status)VALUES('pqr879','2014-07-02','Anny','DELETED')

;WITH CTE AS
(
select distinct x.ID,X.VisitDate,X.Name,X.Status,
ROW_NUMBER()OVER(PARTITION BY x.ID ORDER BY X.Status )As Total from 
(Select a.ID,a.VisitDate,a.Name,a.Status from @T a
GROUP BY a.ID,a.VisitDate,a.Name,a.Status) X 
GROUP BY x.ID,X.VisitDate,X.Name,X.Status
)

Select DISTINCT C.ID,MAX(VisitDate)Dt,C.Name,C.Status from CTE C
WHERE C.Status IS NULL
GROUP BY C.ID,C.Name,C.Status
ORDER BY Dt DESC

答案 4 :(得分:-1)

select id, visitdate,name, status
from table t 
whete t.status <> 'deleted'
相关问题