简体   繁体   中英

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

+---------+------------+
|   Sub   | student_id |
+---------+------------+
| Math    | 0033       |
| Science | 0034       |
| Geom    | 0035       |
| Math    | 0034       |
+---------+------------+

tab 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.

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.

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

sqlFiddle

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.

UPDATED

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

sqlFiddle

If you just want the first row, just add LIMIT 1 to the end of query.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM