SQL count second column for every unique row of first column
I have this table for many, many students for college students and university students
student | subject
-----------------
James | English
James | Physics
Paul | Mathematics
Paul | English
Paul | English
Paul | French
Jake | French
Jake | Mathematics
Paul | English
I need to know a SQL query to get the subject count for each student, for example
student | # of subjects
------------------------
James | 2
Paul | 3
Jake | 2
+3
source to share
5 answers
You need to group
CREATE TABLE `student_subject` (
`name` varchar(256) DEFAULT NULL,
`subject` varchar(256) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `student_subject`
--
INSERT INTO `student_subject` (`name`, `subject`) VALUES
('James', 'English'),
('James', 'Physics'),
('Paul', 'Mathematics'),
('Paul', 'English'),
('Paul', 'English'),
('Paul', 'French'),
('Jake', 'Mathematics'),
('Jake', 'French');
SELECT name, COUNT(distinct subject) AS "subject_count"
FROM student_subject
GROUP BY name,subject order by name desc
#########output##############
Name subject_count
('Jake' , 2),
('James', 2),
('Paul' , 3);
+2
source to share