我有两个表,其中公共列是位置,我正在寻找两个表中的位置计数并显示组合计数。
Table-1
+-------------+
| Location |
+-------------+
| USA |
| INDIA |
| UK |
| INDIA |
+-------------+
Table -2
+-------------+
| Location |
+-------------+
| INDIA |
| INDIA |
| USA |
+-------------+
此处表一的计数是:
+-------------+--------+
| Location | COUNT |
+-------------+--------+
| USA | 1 |
| INDIA | 2 |
| UK | 1 |
+-------------+--------+
表2中的计数是:
+-------------+--------+
| Location | COUNT |
+-------------+--------+
| USA | 1 |
| INDIA | 2 |
+-------------+--------+
这个计数到了:
SELECT Location, COUNT(*) AS COUNT FROM Table-1 GROUP BY Location;
SELECT Location, COUNT(*) AS COUNT FROM Table-2 GROUP BY Location;
但我希望两张表中的组合计数看起来像:
+-------------+--------+
| Location | COUNT |
+-------------+--------+
| USA | 2 |
| INDIA | 4 |
| UK | 1 |
+-------------+--------+
提前谢谢。
答案 0 :(得分:5)
您可以尝试在两个表之间选择UNION ALL
,然后像以前一样使用GROUP BY
计算计数:
SELECT t.Location, COUNT(*) AS COUNT
FROM
(
SELECT Location FROM Table-1
UNION ALL
SELECT Location FROM Table-2
) t
GROUP BY t.Location
答案 1 :(得分:0)
您可以添加虚拟列,然后添加两列
select tt.Location, SUM(count1+count2) from
(
SELECT Location, COUNT(*) count1, 0 AS COUNT2 FROM Table-1 GROUP BY Location;
UNION
SELECT Location, 0 AS COUNT1, COUNT(*) count2 FROM Table-2 GROUP BY Location;
)tt
group by tt.Location
结果,count1是表-1中的总数,count2是表-2中的总数。