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

时间:2015-06-30 19:11:54

标签: tsql duplicates

如果之前有人问过,请道歉。搜索返回的结果看起来特定于我的情况。

我运行以下查询

查询A

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

查询A返回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返回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)) 

返回此错误
Only one expression can be specified in the select list when the subquery is not introduced with EXISTS.

如何恢复查询A中未在查询B中返回的额外记录?

4 个答案:

答案 0 :(得分:1)

The reason for the error is that your subquery is returning too many columns... to solve it change this:

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

to this:

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

Another option would be to use the except set operator which returns the set difference.

答案 1 :(得分:0)

Try this...

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)

Now you have the data in two temporary tables which you should be able to query like this to find the missing record.

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

Don't forget to drop your tables afterward if you need to make adjustments

drop table #temp1
drop table #temp2

答案 2 :(得分:0)

你可以试试这个

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 

答案 3 :(得分:0)

您有语法错误的答案

您使用where

否定左连接

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