views:

96

answers:

1

Hey all,

I have a query that looks like the following:

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

This query simply gives me a list of classes along with the dates they're occurring. The relationship is:

  • a course can have many classes
  • a class can have one course and many class dates
  • a class date can only have one class

What I'd like to add is, for the classes with multiple class dates, add a "counter" that can tell me which "instance" of the class I'm dealing with. So something like:

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

Where the last column is the extra column I'd like to see, indicating that in this scenario, the 2nd row is the second day for this class.

Ideas?

+3  A: 

The OVER clause should give you what you want. From 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
Dave Barker
You need to ORDER BY `cd.startdatetime`, not `c.id` because `c.id` would be the same. And you can only use OVER with ranking functions, like ROW_NUMBER()...
OMG Ponies
That "partition by" is beautiful, didn't know that existed. Thanks!
jvenema