我有一个如下所示的查询:
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
最后一列是我想看的额外列,表示在这种情况下,第二行是这个类的第二天。
想法?
答案 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