来自实例的SQL查询计数

时间:2012-05-23 19:56:56

标签: sql sql-server

我有一张包含公交车和学生注册信息的表格:

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

1 个答案:

答案 0 :(得分: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