Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
94 views
in Technique[技术] by (71.8m points)

sql server - Compare the results of two queries and return missing rows

I have two queries, shown here:

Query #1

select cm 
from cm3
where inactive = 0

Query #2

select cm 
from cm3
join bo on cm3.cm = bo.seller
where status = 'installed'
  and installdate between '20201201' and '20201231'
group by cm
having count(*) > 0

Query #1 returns every seller that is active, while query #2 returns every seller with at least 1 contract installed.

I want to find out which sellers don't have any installed contracts.

I've tried to have query two as a subquery on the WHERE clause and also having both queries separated by an EXCEPT, like shown here.

Sub-query on the WHERE clause

select cm 
from cm3
where cm not in (select cm 
                 from cm3
                 join bo on cm3.cm = bo.seller
                 where status = 'installed'
                   and installdate between '20201201' and '20201231'
                 group by cm
                 having count(*) > 0)

EXCEPT

select * 
from 
    (select cm from cm3 where inactive = 0) as query1
except
select * 
from 
    (select cm 
     from cm3
     join bo on cm3.cm = bo.seller
     where status = 'installed'
       and installdate between '20201201' and '20201231'
     group by cm
     having count(*) > 0) as query2
question from:https://stackoverflow.com/questions/65848855/compare-the-results-of-two-queries-and-return-missing-rows

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To solve this I used EXCEPT, but removed the subqueries:

select cm from cm3 where inactive = 0
except
select cm from cm3
     join bo on cm3.cm = bo.seller
  where status = 'installed'
     and installdate between '20201201' and '20201231'
group by cm
  having COUNT(*) > 0

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...