Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

90
Views
SQL count second column for-each unique row of first column

I have this sample many-to-many table for students & subjects in a university

student | subject
-----------------
James   | English
James   | Physics
Paul    | Mathematics
Paul    | English
Paul    | English
Paul    | French
Jake    | French
Jake    | Mathematics
Paul    | English

I need to know the SQL query for getting the count of subjects for each student like

student | # of subjects
------------------------
James   |   2
Paul    |   3
Jake    |   2
over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

All you need is GROUP BY student and COUNT(DISTINCT):

SELECT student, COUNT(DISTINCT subject) AS "# of subjects" 
FROM students_subjects
GROUP BY student;
over 4 years ago · Santiago Trujillo Report

0

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);
over 4 years ago · Santiago Trujillo Report

0

SELECT student, count(*) 
FROM table
GROUP BY student
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!