按组查询中的最高值

时间:2010-01-19 03:12:19

标签: sql greatest-n-per-group

我知道如何获得最高价值,但我遇到了一些非常简单的问题。

我有一张学生桌。它有:

  • 名称
  • numberoflaps
  • 等级

我希望得到一个查询或报告,显示每个年级圈数最多的前两个孩子。

2 个答案:

答案 0 :(得分:5)

使用MySQL:


MySQL没有任何排名功能,但它确实允许变量创建&更新:

SELECT x.grade,
       x.name,
       x.numberoflaps
  FROM (SELECT s.grade,
               s.name,
               s.numberoflaps,
               CASE 
                 WHEN @grade != s.grade THEN @rownum := 1 
                 ELSE @rownum := @rownum + 1
               END AS rank,
               @grade := s.grade
          FROM STUDENTS s,
               (SELECT @rownum := 0, @grade := NULL) r
      ORDER BY s.grade, s.numberoflaps DESC) x
 WHERE x.rank <= 2
ORDER BY x.grade, x.rank

子查询中的ORDER BY很重要,否则排名将无法正常执行。

使用Oracle 9i + / SQL Server 2005 +:


使用CTE:

WITH laps AS (
  SELECT s.grade, 
         s.name, 
         s.numberoflaps,
         ROW_NUMBER() OVER (PARTITION BY grade ORDER BY numberoflaps DESC) AS rank
    FROM STUDENTS s)
  SELECT l.grade, 
         l.name, 
         l.numberoflaps
    FROM laps l
   WHERE l.rank <= 2
ORDER BY l.grade, l.numberoflaps DESC

非CTE等效物:

  SELECT l.grade, 
         l.name, 
         l.numberoflaps
    FROM (SELECT s.grade, 
                 s.name, 
                 s.numberoflaps,
                 ROW_NUMBER() OVER (PARTITION BY grade ORDER BY numberoflaps DESC) AS rank
            FROM STUDENTS s) l
   WHERE l.rank <= 2
ORDER BY l.grade, l.numberoflaps DESC

警告:

Oracle在9i中获得了排名功能;对于SQL Server,它是2005年。

答案 1 :(得分:2)

SQL Server 2005+版本如下所示:

;WITH Laps_CTE AS
(
    SELECT
        grade, name, numberoflaps,
        ROW_NUMBER() OVER (
            PARTITION BY grade
            ORDER BY numberoflaps DESC
        ) AS RowNum
    FROM students
)
SELECT grade, name, numberoflaps
FROM Laps_CTE
WHERE RowNum <= 2

如果那不是你的方言,请告诉我们是什么。