假设name
两个表中的值相同的一种选择是
SELECT t1.name, t2.cnt - t1.cnt diff
FROM( SELECT name, COUNT(name) cnt
FROM table1
group by name ) t1,
( SELECT name, COUNT(name) cnt
FROM table2
group by name ) t2
WHERE t1.name = t2.name
如果您想处理一个表具有而另一个表name
没有但您不知道哪个表具有额外名称的情况(并假设您想说另一个表的 acnt
为 0 name
)
SELECT coalesce(t1.name, t2.name) name,
nvl(t1.cnt, 0 ) t1_cnt,
nvl(t2.cnt, 0 ) t2_cnt,
nvl(t2.cnt,0) - nvl(t1.cnt,0) diff
FROM( SELECT name, COUNT(name) AS cnt
FROM table1
group by table1.name ) t1
full outer join
( SELECT name, COUNT(name) AS cnt
FROM table2
group by table2.name ) t2
on( t1.name = t2.name )
您可以在此SQLFiddle中看到