我有一张桌子,上面有公共汽车和学生的报名信息:

CREATE TABLE [dbo].[BusSignupInstance](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [StudentId] [int] NOT NULL,
    [BusId] [int] NOT NULL
) ON [PRIMARY]


以下是一些示例数据:

Id  StudentId   BusId
1   1   1
2   2   1
3   3   1
4   1   2
5   4   2
6   1   3
7   5   3


我想要按总线ID的总数。在这种情况下将是:

BusId    Num of Students
1      2 (student id 2, 3)
2      1 (student id 4)
3      2 (student id 1, 5)


结果基于注册的顺序,如果学生1进行3次注册,则只有最后一次有效。

最佳答案

SELECT  busId, COUNT(*)
FROM    (
        SELECT  busId, studentId,
                ROW_NUMBER() OVER (PARTITION BY studentId ORDER BY id DESC) rn
        FROM    busSignupInstance
        ) q
WHERE   rn = 1
GROUP BY
        busId

10-04 11:17