Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Count unique rows where a column contains two different values

I have taken a good look around and not been able to find any questions that match mine. Maybe I am not using the right language when searching or whatever, but here goes.

I have an SQL table called Classes that looks something like this

Student_Name | Class  
--------------------  
Edgar        | Chemistry  
Allan        | Chemistry  
Burt         | Chemistry  
Edgar        | Math  
Sue          | Math  
Hamilton     | Math  
Edgar        | English  
Sue          | English  
Edgar        | German  
Ben          | German  

I want to count how many students are taking both Math and German.

Assuming the following in this example: - Student names are unique - One student can have many classes

Logically I would use a select statement to get a result set of students who are taking Math. Then I would go through each Student_Name from the result set and check them against the table to see how many are taking German.

In this case I would expect a return of 1 as only Edgar is taking both Math and German.

Here are some of the queries I have tried so far to no avail :-(

This one was after doing some research on DISTINCT:

SELECT COUNT(DISTINCT Student_Name) FROM Classes WHERE Class = 'Math' AND Class = 'German';

And this one was after finding out more about GROUP BY:

SELECT COUNT(*) FROM (
    SELECT DISTINCT Student_Name FROM Classes 
    WHERE Class IN ( 'Math', 'German' ) 
    GROUP BY Student_Name
);

Neither of these came out quite right any help would be highly appreciated.

like image 404
onmylemon Avatar asked Apr 15 '26 03:04

onmylemon


2 Answers

SELECT  COUNT(*) totalStudent
FROM
        (
            SELECT  student_name
            FROM    Classes
            WHERE   class IN ('Math','German')
            GROUP   BY student_name
            HAVING  COUNT(*) = 2
        ) subAlias
  • SQLFiddle Demo

OUTPUT

╔══════════════╗
║ TOTALSTUDENT ║
╠══════════════╣
║            1 ║
╚══════════════╝
like image 137
John Woo Avatar answered Apr 17 '26 18:04

John Woo


Could also do the following:

select count(distinct a.Student_name)
from Classes a inner join Classes b on
     a.Class = 'German' and
     b.Class = 'Math'   and
     a.Student_Name = b.Student_name;

This solves the problem where the table contains duplicate rows (as pointed out by a commenter to another answer)

like image 21
NealB Avatar answered Apr 17 '26 17:04

NealB



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!