Result1 Result2
a a
b b
a
如何通过在这两个结果集之间进行减法来获取a
。 NOT EXISTS
和NOT IN
不会为这两个结果集返回任何内容。但是我希望返回a
。请帮助!
答案 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
两次,则上述查询也会返回两次。