[英]SQL Server - Removing duplicates
这是我的桌子。 我想删除具有相应“已删除”状态的记录。 请参见输出示例:
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
请尝试使用CTE:
with c as
(
select
*,
row_number() over(partition by id order by Status) as n
from tbl
)
delete from c
where n > 1;
我认为您希望保留自上次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;
要删除状态为“已删除”的记录,请使用以下命令:
DELETE FROM TableName WHERE status = 'deleted'
另外,您的预期输出看起来像只希望显示最大访问日期,因此您可以在运行DELETE之后使用以下SELECT查询。
SELECT ID, MAX(VisitDate) AS VisitDate, Name, Status
FROM TableName
GROUP BY ID, Name, Status
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
select id, visitdate,name, status
from table t
whete t.status <> 'deleted'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.