【问题标题】:How to aggregate top 5 numbers in SQL Server 2000如何聚合 SQL Server 2000 中的前 5 个数字
【发布时间】:2013-11-15 20:36:55
【问题描述】:

您好,我遇到了一个问题,学生可以有超过 5 门科目,但我只需将学生获得最高的 5 门科目总分相加。表示任何学生获得的前 5 名总分之和的一种方式。

我该如何进行,请帮助我。提前致谢。

【问题讨论】:

    标签: sql sql-server tsql sql-server-2000


    【解决方案1】:

    在 SQL 2000 中,您需要使用子选择来确定有多少具有相同 ID 的行具有更高的标记。然后过滤其上方有少于 5 个高标记行的行:

    select 
      ID, Sum(Mark)
    From Table1 t
    where 
    (Select count(*) 
         from Table1 it 
        where it.id=t.id and it.mark>t.mark) <5
    group by ID
    

    【讨论】:

    • @Jaan 那么您需要更好地定义您要查找的内容。将您想要的结果添加到问题中。我们不是读心者。
    【解决方案2】:

    ROW_NUMBER 不幸不在 sql-server-2000 中。不过,您可以使用子查询获得相同的结果。希望这是您正在寻找的:

    SELECT s.studentid, SUM(s.total_marks)
    FROM students s
    WHERE s.sub_code IN (SELECT TOP 5 sub_code 
                         FROM students a 
                         WHERE a.studentid = s.studentid
                         ORDER BY total_marks DESC)
    GROUP BY studentid
    

    Working in fiddle

    【讨论】:

      【解决方案3】:

      这是一个查询,只为您提供每位学生的 5 个最高分:

        SELECT studentID, total_marks, 
               row_number() OVER (PARTITION BY studentID, ORDER BY total_marks DESC) as rowN
        FROM studentTable
        WHERE rowN <= 5
      

      所以要得到总数:

      SELECT studentID, SUM(total_marks)
      FROM
      (      
        SELECT studentID, total_marks, 
               row_number() OVER (PARTITION BY studentID, ORDER BY total_marks DESC) as rowN
        FROM studentTable
        WHERE rowN <= 5
      ) T
      GROUP BY studentID
      

      【讨论】:

      • 感谢 Hogan 帮助我...我收到错误消息,因为“row_number 不是识别功能”。我正在使用 SQL Server 2000
      • @Jaan - 此功能在 SQL 2000 中不可用。该产品已有 15 年历史。
      猜你喜欢
      • 2017-01-29
      • 2011-08-23
      • 2011-01-25
      • 2013-08-14
      • 1970-01-01
      • 1970-01-01
      • 2010-11-17
      • 1970-01-01
      • 2020-06-08
      相关资源
      最近更新 更多