代码之家  ›  专栏  ›  技术社区  ›  Caveatrob

获取其计数与类别的最大(计数)匹配的记录

  •  0
  • Caveatrob  · 技术社区  · 15 年前

    course  SECTION  grade  gradeCount
    -----------------------------------
    1301    001      C      3
    1301    001      C+     3
    1301    001      C-     4
    1301    001      D      5
    1301    001      D+     3
    1301    001      D-     2
    1301    001      F      18
    1301    002      A-     1
    1301    002      B      1
    1301    002      B-     3
    1301    002      C      2
    

    我想得到一份每个年级人数最多的课程/部分的清单。

    例如:

    Grade|Course|Section|Count
    A | 1301| 023 | 75     // 1301-023 had the most A's, 75 of them
    B | 1301| 033 | 65     // 1301-033 had the most B's, 65 of them
    

    4 回复  |  直到 15 年前
        1
  •  1
  •   Stephen Turner    15 年前

    假设gradeCount已经是每个唯一课程、节和年级的总成绩。

    首先找出每个年级的最高分数

    SELECT
        grade,
        Max(gradeCount) as MaxGradeCount
    FROM
        table
    

    然后查找原始表中哪些行具有最大坡度

    SELECT
        course,
        section,
        grade,
        gradeCount
    FROM
        table
    
            INNER JOIN
        (SELECT
            grade,
            Max(gradeCount) as MaxGradeCount
        FROM
            table
        ) MaxGrades
            ON  table.grade = MaxGrades.grade
                AND table.gradeCount = MaxGrades.MaxGradeCount
    ORDER BY 
        table.grade
    

    一个简单的内部连接,看不到CTE;-)

        2
  •  2
  •   Andomar    15 年前

    假设 CTE :

    declare @Test table (
        course char(4),
        section char(3),
        grade char(2),
        gradeCount int
    )
    
    insert into @Test
        values ('1301','001','A',100),
               ('1301','002','A',20),
               ('1301','001','B',10),
               ('1301','002','B',50),
               ('1301','003','B',50)
    
    ;with cteMaxGradeCount as (
        select grade, max(gradeCount) as MaxGradeCount
            from @Test
            group by grade
    )
    select t.course, t.SECTION, t.grade, t.gradeCount
        from cteMaxGradeCount c
            inner join @Test t
                on c.grade = t.grade
                    and c.MaxGradeCount = t.gradeCount
        order by t.grade
    
        3
  •  0
  •   Andomar    15 年前

    not exists 要仅筛选出计数最高的分数:

    ; with s as 
        (
        select  course
        ,       section
        ,       left(grade,1) as Grade
        ,       sum(gradeCount) sumGradeCount
        from    YourTable yt1
        group by
                course
        ,       section
        ,       left(grade,1)
        )
    select  *
    from    s s1
    where   not exists
            (
            select  *
            from    s s2
            where   s1.course = s2.course
                    and s1.section = s2.section
                    and s1.sumGradeCount < s2.SumGradeCount
            )
    
        4
  •  -3
  •   Koteswara sarma    15 年前

    可以将GroupBy与聚合函数-max()、count()结合使用。