[英]Sql query for union of 2 tables
I am stuck with a query. 我陷入了疑问。 I have two tables and both have one column in common, but the data in both may differ:
我有两个表,并且两个表都有一个共同的列,但是两个表中的数据可能不同:
tab 1 标签1
+---------+------------+
| Sub | student_id |
+---------+------------+
| Math | 0033 |
| Science | 0034 |
| Geom | 0035 |
| Math | 0034 |
+---------+------------+
tab 2 标签2
+---------+----------+
| Sub | class_id |
+---------+----------+
| Science | 001 |
| Geom | 002 |
| Geom | 001 |
| Civics | 004 |
+---------+----------+
Now I need the results in the following way: 现在,我需要通过以下方式获得结果:
+---------+----------------+--------------+
| Sub | Student(count) | Class(count) |
+---------+----------------+--------------+
| Math | 2 | 0 |
| Science | 1 | 1 |
| Geom | 1 | 2 |
| Civics | 0 | 1 |
+---------+----------------+--------------+
I think I have to use union and I can get results in two different queries, but I am not able to show the final table as above. 我想我必须使用union,并且可以在两个不同的查询中获得结果,但是无法显示上述最终表。
This is what I have: 这就是我所拥有的:
select sub,count(*)as student_id from tab1
group by sub
union
select sub,count(*)as class_id from tab2
group by sub
But I get 2 cols out of it instead of 3. 但是我得到的是2列而不是3列。
Any help will be appreciated. 任何帮助将不胜感激。
try this one 试试这个
SELECT AllSubs.Sub as Sub,
COUNT(DISTINCT tab1.Student_Id) as "Student(Count)",
COUNT(DISTINCT tab2.Class_Id) as "Class(Count)"
FROM
(SELECT DISTINCT Sub FROM tab1
UNION
SELECT DISTINCT Sub FROM tab2)AllSubs
LEFT JOIN tab1 ON tab1.Sub = AllSubs.Sub
LEFT JOIN tab2 ON tab2.Sub = AllSubs.Sub
GROUP BY AllSubs.Sub
the query select all distinct subjects from tab1 and tab2 then left joins with tab1 and tab2, then counts distinct studdent_id and counts distinct class_id grouping by subject. 该查询从tab1和tab2中选择所有不同的主题,然后与tab1和tab2左连接,然后计算不同的studdent_id并按主题对不同的class_id进行计数。
SELECT AllSubs.Sub as Sub,
COUNT(DISTINCT tab1.Student_Id) as "Student(Count)",
COUNT(DISTINCT tab2.Class_Id) as "Class(Count)",
COUNT(DISTINCT tab1.Student_Id) - COUNT(DISTINCT tab2.Class_Id) as difference
FROM
(SELECT DISTINCT Sub FROM tab1
UNION
SELECT DISTINCT Sub FROM tab2)AllSubs
LEFT JOIN tab1 ON tab1.Sub = AllSubs.Sub
LEFT JOIN tab2 ON tab2.Sub = AllSubs.Sub
GROUP BY AllSubs.Sub
ORDER BY difference DESC
If you just want the first row, just add LIMIT 1
to the end of query. 如果只需要第一行,只需在查询末尾添加
LIMIT 1
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.