我正在尝试将匹配的id的values_occurrence加在一起。例如,ID号1具有3而另一个记录显示ID号1具有4.我想基于ID匹配来添加3 + 4。
我试图查看哪个ID在每个表中的条目最多,然后将它们一起添加。
ID value_occurrence
--------------------
1 3
1 4
到目前为止,这就是我所拥有的。
SELECT ID, COUNT(ID) AS value_occurrence
FROM TABLE1
GROUP BY ID
UNION
SELECT ID, COUNT(ID) AS value_occurrence
FROM TABLE2
GROUP BY ID
ORDER BY ID ASC;
任何帮助将不胜感激。
答案 0 :(得分:2)
执行union all
然后汇总:
select id, count(*) as total_cnt, sum(t1) as t1_cnt, sum(t2) as t2_cnt
from ((select id, 1 as t1, 0 as t2 from table1) union all
(select id, 0, 1 from table2)
) t
group by id
order by id;