5

给定一个名为“等级”的表:

STUDENT  GRADE
john     94
john     76
john     83
john     87
john     90

我想要一个查询来返回每个学生的一些成绩示例,例如:

STUDENT    GRADE1  GRADE2   GRADE3  GRADE4
John       94      76       83      87

请注意,仅返回 4 个示例成绩列,但该学生的成绩超过 4 个。

我只知道如何在 GROUP BY 子句中使用 min() 和 max() 函数返回 2 个示例成绩:

select student, min(grade), max(grade) 
from grades
group by student

除了 min/max 之外,是否有任何技巧或功能可以使用 GROUP BY 子句显示超过 2 个等级?

我宁愿不编写自己的存储函数来执行此操作,除非它是查询的一部分而不是存储在数据库中。

我正在考虑从记录集中返回除 MIN 和 MAX 之外的其他值的更多函数(如第二高、第三高等)。

想法?

4

2 回答 2

6

您可以通过应用row_number()函数然后应用 PIVOT 来获得结果:

select student, 
  grade1 = [1], 
  grade2 = [2], 
  grade3 = [3], 
  grade4 = [4]
from
(
  select student, grade,
    row_number() over(partition by student
                      order by grade desc) seq
  from grades
) d
pivot
(
  max(grade)
  for seq in ([1], [2], [3], [4]) -- the # of grades you want returned
) piv;

请参阅SQL Fiddle with Demo

PIVOT 中使用的新列名称将是您想要返回的成绩数。分区中使用的ORDER BY是 by grade desc,但您也可以查看 usingorder by newid()以获取返回的随机结果

这也可以使用带有 CASE 表达式的聚合函数来完成:

select student,
  max(case when seq = 1 then grade end) grade1,
  max(case when seq = 2 then grade end) grade2,
  max(case when seq = 3 then grade end) grade3,
  max(case when seq = 4 then grade end) grade4
from
(
  select student, grade,
    row_number() over(partition by student
                      order by newid()) seq
  from grades
) d
group by student;

请参阅带有演示的 SQL Fiddle

于 2013-10-29T17:11:42.573 回答
0

我提出这样的建议。唯一的限制是您不能显示示例 1 到 n,您仅限于确定的数量。

SELECT DISTINCT student, 
(
    select top 1 grade from
    (select grade, ROW_NUMBER() OVER(ORDER BY grade DESC) AS Row from grades g2 where g.student = g2.student) a where a.Row = 1
) AS GRADE1  ,
(
    select top 1 grade from
    (select grade, ROW_NUMBER() OVER(ORDER BY grade DESC) AS Row from grades g2 where g.student = g2.student) a where a.Row = 2
) AS GRADE2,
(
    select top 1 grade from
    (select grade, ROW_NUMBER() OVER(ORDER BY grade DESC) AS Row from grades g2 where g.student = g2.student) a where a.Row = 3
) AS GRADE3,
(
    select top 1 grade from
    (select grade, ROW_NUMBER() OVER(ORDER BY grade DESC) AS Row from grades g2 where g.student = g2.student) a where a.Row = 4
) AS GRADE4
from grades g

带游标。在此解决方案中,您将获得 1 到 n 个结果

DECLARE @grade int
DECLARE @n int

DECLARE @sql varchar(max)

DECLARE _cursor CURSOR FOR 
     SELECT grade
     FROM grade
     WHERE student like 'XXX'

OPEN _cursor
FETCH NEXT FROM _cursor INTO @grade
WHILE @@FETCH_STATUS = 0
BEGIN
    IF @sql like ''
    begin
         set @sql = 'SELECT ' + 'XXX' + ' AS Student '
    end
    set @sql = @sql + ',' + @grade ' as GRADE'+  @n
    set @n = @n + 1
END

CLOSE _cursor
DEALLOCATE _cursor

exec(@sql)

这个输出将是

STUDENT    GRADE1  GRADE2   GRADE3  GRADE4
John       94      87       83      76
于 2013-10-29T17:04:05.753 回答