如果两个计数匹配,则删除记录

时间:2018-07-03 14:25:15

标签: sql sql-server

我有下表的数据

+---------+--------+--------+
| Trans   | Status | Step   |
+---------+--------+--------+
| ABCDE   | Comple | 1
+---------+--------+--------+
| ABCDE   | Error  | 2
+---------+--------+--------+
| FGHIJ   | Comple | 1
+---------+--------+--------+
| FGHIJ   | Comple | 2
+---------+--------+--------+
| KLMNO   | Comple | 1
+---------+--------+--------+
| KLMNO   | Comple | 2
+---------+--------+--------+

我只想删除trans和status ='comple'的计数与trans的计数相同的记录

我可能会做一个游标和循环,但这是我不想做的事。

按照计数的思路思考,但可能相距甚远。

谢谢

我只想删除FGHIJ和KLMNO,因为我知道已完成所有步骤。

我要保留abcde,因为并非所有步骤都已完成

4 个答案:

答案 0 :(得分:1)

这是您想要的吗?

--delete 
select *
from yourtable t
where not exists
(
    select 1
    from yourtable t2
    where t1.Trans=t2.Trans
    and status<>'Comple'
)

首先使用它,以确保要删除的内容,然后注释掉SELECT并取消注释删除

答案 1 :(得分:1)

DELETE FROM tbl
WHERE  Trans IN ( SELECT trans
                  FROM   tbl
                  GROUP  BY Trans
                  HAVING COUNT(*) = SUM(CASE WHEN status = 'Comple' THEN 1 ELSE 0 END) ) 

它删除行(通过对Trans进行过滤),其中一组trans中的行数等于具有Comple状态的该组中的行数

http://sqlfiddle.com/#!18/1768b/10

答案 2 :(得分:0)

尝试一下

DECLARE @Data AS TABLE (Trans Varchar(10)   , Status  Varchar(10) , Step INT   )
INSERT INTO @Data
SELECT 'ABCDE', 'Comple' , 1 UNION ALL
SELECT 'ABCDE', 'Error'  , 2 UNION ALL
SELECT 'FGHIJ', 'Comple' , 1 UNION ALL
SELECT 'FGHIJ', 'Comple' , 2 UNION ALL
SELECT 'KLMNO', 'Comple' , 1 UNION ALL
SELECT 'KLMNO', 'Comple' , 2

SELECT * FROM @Data

;WITH CTe
AS
(
SELECT * , ROW_NUMBER()OVER(PArtition by Trans   , [Status] ORDER BY  Trans) AS TwocountsMatch
FROM @Data
)
DELETE FROM CTe WHERE TwocountsMatch=2 AND [Status]='Comple'


SELECT * FROM @Data

演示结果:http://rextester.com/TYK92230

答案 3 :(得分:0)

如果我对您的理解正确,那么您想删除所有[Trans]行,如果所有这些行[status]'Comple'吗?

DECLARE @Data AS TABLE (Trans Varchar(10)   , Status  Varchar(10) , Step INT   )

INSERT INTO @Data
SELECT 'ABCDE', 'Comple' , 1 UNION ALL
SELECT 'ABCDE', 'Error'  , 2 UNION ALL
SELECT 'FGHIJ', 'Comple' , 1 UNION ALL
SELECT 'FGHIJ', 'Comple' , 2 UNION ALL
SELECT 'KLMNO', 'Comple' , 1 UNION ALL
SELECT 'KLMNO', 'Comple' , 2

SELECT * FROM @Data;

WITH
  summarised
AS
(
  SELECT
    * ,
    COUNT(*) OVER (PARTITION BY [trans]          )   AS count_trans,
    COUNT(*) OVER (PARTITION BY [trans], [status])   AS count_trans_status
  FROM
    @Data
)
DELETE
  summarised
WHERE
  [status] = 'Comple'
  AND count_trans = count_trans_status
;

SELECT * FROM @Data