3

我有一个包含公共汽车和学生注册信息的表格:

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次,只有最后一次有效。

4

1 回答 1

6
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
于 2012-05-23T19:58:07.167 回答