查找两个相似查询之间的结果差异

Find difference in results between two similar queries

如果之前有人问过这个问题,我们深表歉意。 return 的搜索结果看起来很适合我的情况。

我运行以下查询

查询 A

select c.caseid
from customer c
where left(c.workercd,1) = 'V'
and c.enddate is null

查询 A returns 199 个结果。

查询 B

select c.caseid, p.* 
from customer c
left outer join payment p on c.CaseID = p.caseid
--inner join paymenttypelookup ptl on p.paymenttypeid = ptl.paymenttypeid
where left(c.workercd,1) = 'V'
and c.enddate is null
and (p.paymenttypeid not between 9 and 13 or p.paymenttypeid is null)

查询 B returns 198 个结果。

我正在寻找额外的记录。使用此查询

select * 
from 
    (select c.caseid
    from customer c
    where left(c.workercd,1) = 'V'
    and c.enddate is null) as temp
where temp.caseid not in
    (select c2.caseid, p.* 
    from customer c2
    left outer join payment p on c2.CaseID = p.caseid
    --inner join paymenttypelookup ptl on p.paymenttypeid = ptl.paymenttypeid
    where left(c2.workercd,1) = 'V'
    and c2.enddate is null
    and (p.paymenttypeid not between 9 and 13 or p.paymenttypeid is null)) 

Returns这个错误
Only one expression can be specified in the select list when the subquery is not introduced with EXISTS.

如何恢复查询 A 中没有 return 查询 B 中的额外记录?

错误的原因是你的子查询返回了太多的列...要解决它改变这个:

where temp.caseid not in (select c2.caseid, p.* from customer c2

对此:

where temp.caseid not in (select c2.caseid from customer c2

另一种选择是使用 except 集合运算符,returns 集合差异。

试试这个...

select c.caseid
into #temp1
from customer c
where left(c.workercd,1) = 'V'
and c.enddate is null

select c.caseid, p.* 
into #temp2
from customer c
left outer join payment p on c.CaseID = p.caseid
--inner join paymenttypelookup ptl on p.paymenttypeid = ptl.paymenttypeid
where left(c.workercd,1) = 'V'
and c.enddate is null
and (p.paymenttypeid not between 9 and 13 or p.paymenttypeid is null)

现在您在两个临时表中有了数据,您应该能够像这样查询以找到丢失的记录。

select * from #temp1 t1 
left join #temp2 t2 on t1.caseid = t2.caseid 
where t2.caseid is null

如果您需要进行调整,请不要忘记在之后放下您的桌子

drop table #temp1
drop table #temp2

你可以试试这个

SELECT
    c.*
FROM
    customer c
    LEFT JOIN payment p ON c.caseid = p.caseid
                           AND (p.paymenttypeid NOT BETWEEN 9 AND 13
                                OR p.paymenttypeid IS NULL)
WHERE
    LEFT(c.workercd,1) = 'V'
    AND c.enddate IS NULL
    AND p.caseid IS NULL 

你有一个语法错误的答案

你用 where

否定左连接

我打赌额外的行有 p.paymenttypeid 在 9 和 13 之间