如何在 SQL 中查找不成对的行?

How to find unpaired rows in TSQL?

使用 2008 R2。

我的 table 应该包含一些成对的行 - 一个取消事务和一个添加事务,但是我们有一些只有取消的错误数据。

我正在尝试识别并消除它们。我尝试了以下代码,但 SQL 返回了错误 "All queries combined using a UNION, INTERSECT or EXCEPT operator must have an equal number of expressions in their target lists."

如何识别这些不匹配的行?

select *
from dbo.mytable t
where typename = 'Cancel'
except
Select *
from dbo.mytable t1 
inner join dbo.mytable t2
    on t1.id = t2.id
where t1.typename = 'Cancel'
and t2.typename = 'Add'

您必须在 select 列表中指定 id 字段:

SELECT id
FROM mytable
WHERE typename = 'Cancel'

EXCEPT

SELECT id
FROM mytable
WHERE typename = 'Add'

上述查询 select 是存在不匹配 'Cancel' 记录的 id 值。

或者您可以使用 LEFT JOIN:

SELECT t1.id
FROM mytable t1
LEFT JOIN mytable t2 ON t1.id = t2.id AND t2.typename = 'Add'
WHERE t1.typename = 'Cancel' AND t2.id IS NULL

试试这个:

select id
from dbo.mytable t
where typename = 'Cancel'
except
Select id
from dbo.mytable t1 
inner join dbo.mytable t2
    on t1.id = t2.id
where t1.typename = 'Cancel'
and t2.typename = 'Add'
SELECT  *
FROM    (
        SELECT  *,
                SUM(CASE typename WHEN 'add' THEN 1 END) OVER (PARTITION BY id) addcnt,
                SUM(CASE typename WHEN 'cancel' THEN 1 END) OVER (PARTITION BY id) cancelcnt
        FROM    mytable
        ) q
WHERE   addcnt IS NULL
        AND cancelcnt > 0

这将 select 所有有取消但没有添加的交易,包括其他可能的类型。