减去两个结果集SQL

时间:2016-06-03 10:38:01

标签: sql sql-server-2012

Result1     Result2
a           a
b           b    
a

如何通过在这两个结果集之间进行减法来获取aNOT EXISTSNOT IN不会为这两个结果集返回任何内容。但是我希望返回a。请帮助!

2 个答案:

答案 0 :(得分:2)

嗯。嗯。 。 。这很棘手,因为您想要考虑计数。一种方法是:

select r1.col, r1.cnt - coalesce(r2.cnt, 0)
from (select col, count(*) as cnt
      from result1
      group by col
     ) r1 left join
     (select col, count(*) as cnt
      from resuult2
      group by col
    ) r2
    on r1.col = r2.col
where r1.cnt > coalesce(r2.cnt, 0);

这并不能完全返回您想要的内容,但它可能就足够了。另一种方法是使用row_number()

select r1.col
from (select col, row_number() over (partition by col order by col) as seqnum
      from result1
      group by col
     ) r1 left join
     (select col, row_number() over (partition by col order by col) as seqnum
      from resuult2
      group by col
    ) r2
    on r1.col = r2.col and r1.seqnum = r2.seqnum
where r2.col is null;

答案 1 :(得分:2)

使用标准SQL,您可以使用except all运算符:

select *
from table_one
except all
select * 
from table_two

SQLFiddle:http://sqlfiddle.com/#!15/d998c/1

请注意,如果您在a中有table_one两次,则上述查询也会返回两次。