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

时间:2010-10-25 20:57:36

标签: sql sql-server tsql aggregate-functions

考虑以下课程,课程部分的分数,成绩,分数:

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 个答案:

答案 0 :(得分:2)

至少假设CTE的SQL Server 2005:

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

答案 1 :(得分:1)

假设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 :(得分:0)

您可以在公用表格表达式(CTE)中计算每个字母等级的总和。然后,您可以使用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
        )

答案 3 :(得分:-3)

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

- 干杯