SQL中的子组计数

时间:2009-11-19 23:49:34

标签: sql sql-server-2005

我有一个如下所示的查询:

select
    c.[Name], 
    c.Description, 
    c.ID,
    cd.StartDateTime
from
    Classroom.dbo.Class as c
left join
    Classroom.dbo.Course as co
on
    co.ID = c.CourseID
left join
    Classroom.dbo.Classdate as cd
on
    cd.ClassID = c.ID
where
    co.PublicIndicator = 1

这个查询只是给我一个类列表以及它们发生的日期。关系是:

  • 课程可以有很多课程
  • 课程可以有一门课程和多个课程日期
  • 班级日期只能有一个班级

我想补充的是,对于具有多个类日期的类,添加一个“计数器”,可以告诉我正在处理的类的“实例”。如下所示:

Test    test    1   2009-08-19 05:00:00     1
Test    test    1   2009-08-20 05:00:00     2
Test    a       2   2009-10-22 08:00:00     1
Test    a       3   2009-10-30 07:00:00     1
Test    a       5   2009-10-21 11:00:00     1

最后一列是我想看的额外列,表示在这种情况下,第二行是这个类的第二天。

想法?

1 个答案:

答案 0 :(得分:3)

OVER子句应该给你你想要的东西。来自MSDN

SELECT c.[Name], c.Description, c.ID, cd.StartDateTime, 
       ROW_NUMBER() OVER(PARTITION BY c.Id Order BY cd.StartDateTime)
  FROM Classroom.dbo.Class as c
  LEFT JOIN Classroom.dbo.Course as co
    ON co.ID = c.CourseID
  LEFT JOIN Classroom.dbo.Classdate as cd
    ON cd.ClassID = c.ID
 WHERE co.PublicIndicator = 1