使用Row_Number() - 查找最大注册

时间:2012-03-14 07:26:04

标签: sql-server-2005 tsql

我想使用row_number()函数找出每门课程的最大试卷注册。

注册表

CourseID  StudentName  PaperCode

 101    David   10001
 101    David   20000
 101    George  10000
 102    Peter   10000
 102    Peter   20000
 102    David   20000

预期结果可能是

CourseID| StudentName | NumberofRegistration

101       David     2
102      Peter       2   

我尝试使用以下查询,无法扩展它以获得所需的结果。

select 

         CourseID,
         StudentName,
         NumberOfRegistration
from

(
  select 
         CourseID,
         StudentName,
         ROW_NUMBER() 
         over( 
              partition by count(papercode)
              order by CourseID asc) as NumberOfRegistration

这          注册         按CourseID,StudentName分组  )X

请帮我完成。

2 个答案:

答案 0 :(得分:3)

declare @T table
(
  CourseID int,
  StudentName varchar(10),
  PaperCode int
)

insert into @T values
(101,    'David',   10001),
(101,    'David',   20000),
(101,    'George',  10000),
(102,    'Peter',   10000),
(102,    'Peter',   20000),
(102,    'David',   20000)

select CourseID, StudentName, NumberofRegistration
from
  (
    select CourseID, StudentName, NumberofRegistration,
           row_number() over(partition by CourseID order by NumberofRegistration desc) as rn
    from
      (
        select CourseID, StudentName, count(*) as NumberofRegistration
        from @T
        group by CourseID, StudentName
      ) as T
  ) as T
where rn = 1

答案 1 :(得分:3)

也许是这样的:

测试数据

DECLARE @tbl TABLE(CourseID INT,StudentName VARCHAR(100),PaperCode INT)

INSERT INTO @tbl
VALUES
    (101,'David',10001),
    (101,'David',20000),
    (101,'George',10000),
    (102,'Peter',10000),
    (102,'Peter',20000),
    (102,'David',20000)

查询

像Mikael Eriksson所说,这将适用于SQL Server 2005/2008。但它在SQL Server 2012中不起作用。

;WITH CTE
AS
(
    SELECT
        ROW_NUMBER() OVER(PARTITION BY tbl.CourseID ORDER BY tbl.CourseID) AS RowNumber,
        COUNT(PaperCode) OVER(PARTITION BY tbl.CourseID, tbl.[StudentName]) AS NumberofRegistration,
        CourseID,
        StudentName,
        PaperCode
    FROM
        @tbl AS tbl
)
SELECT
    CTE.CourseID,
    CTE.StudentName,
    CTE.NumberofRegistration
FROM
    CTE
WHERE
    CTE.RowNumber=1

但这可以在SQL Server 2012中使用:

;WITH CTE
AS
(
    SELECT
        COUNT(CourseID) OVER(PARTITION BY tbl.CourseID,tbl.StudentName) AS NumberofRegistration,
        tbl.CourseID,
        tbl.StudentName,
        tbl.PaperCode
    FROM
        @tbl AS tbl 
)
, CTE2
AS
(
    SELECT
        ROW_NUMBER() OVER(PARTITION BY CTE.CourseID ORDER BY CTE.NumberofRegistration DESC) AS RowNumber,
        CTE.NumberofRegistration,
        CTE.CourseID,
        CTE.StudentName,
        CTE.PaperCode
    FROM
        CTE
)
SELECT
    CTE2.CourseID,
    CTE2.StudentName,
    CTE2.NumberofRegistration
FROM
    CTE2
WHERE
    CTE2.RowNumber=1

<强>结果

CourseID| StudentName | NumberofRegistration
101       David           2
102       Peter           2