How to count distinct values from two columns into one number

Aurel Drejta :

The two tables I'm working on are these:

Submissions:

+----+------------+
| id | student_id |
+----+------------+
|  1 |          1 |
|  2 |          2 |
|  3 |          3 |
+----+------------+

Group_submissions:

+----+---------------+------------+
| id | submission_id | student_id |
+----+---------------+------------+
|  1 |             1 |          2 |
|  2 |             2 |          1 |
+----+---------------+------------+

Only one student actually makes the submission and goes into the submissions table while the others go to the group_submissions table(if the submission is a group submission)

I want to count the unique number of students that have made submission either as a group or alone

I want just the number to be returned in the end (3 based on the data on the tables above)

A student that is in the submissions table should not be counted twice if he is in the group_submission table and vice-versa.

Also students that only have done individual submissions(that are not in the group_submissions table) also should be counted regardless if the have ever been in a group submission

I'm already doing some other operations on these table in a query I'm building so if you can give me a solution based on joining these two tables that would help.

This is what i have tried:

count(distinct case when group_submissions.student_id is not null then group_submissions.student_id end) + count(distinct case when submissions.student_id is not null then submissions.student_id end)

But it gives me duplicates so if a student is in both tables he is counted two times.

Any ideas?

NOTE: This is a MySQL database.

Gordon Linoff :

I think you want union and a count:

select count(*)
from ((select student_id
       from submissions
      ) 
      union   -- on purpose to remove duplicates
      (select student_id
       from group_submissions
      )
     ) s;

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=173960&siteId=1