SQL计数第二列 - 第一列的每个唯一行

时间:2017-04-18 06:12:47

标签: mysql sql postgresql

我为学生提供了这个样本多对多表格&大学的科目

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

我需要知道SQL查询,以获取每个学生的主题数量,如

student | # of subjects
------------------------
James   |   2
Paul    |   3
Jake    |   2

5 个答案:

答案 0 :(得分:3)

您需要的只是GROUP BY studentCOUNT(DISTINCT)

SELECT student, COUNT(DISTINCT subject) AS "# of subjects" 
FROM students_subjects
GROUP BY student;

答案 1 :(得分:2)

您需要分组

$(function(){
$(".dropdown").hover(            
        function() {
            $('.dropdown-menu', this).stop( true, true ).fadeIn("fast");
            $(this).toggleClass('open');
            $('b', this).toggleClass("caret caret-up");                
        },
        function() {
            $('.dropdown-menu', this).stop( true, true ).fadeOut("fast");
            $(this).toggleClass('open');
            $('b', this).toggleClass("caret caret-up");                
        });
});

答案 2 :(得分:-2)

SELECT student, count(*) 
FROM table
GROUP BY student

答案 3 :(得分:-2)

您需要按学生分组:

SELECT student, count(*) as NumberOfSubjects
FROM table_name
GROUP BY student

答案 4 :(得分:-3)

Select student , count(subject) from Table Group by student