我的问题类似于: How do you group by one column and retrieve a row with the minimum value of another column in T/SQL?
首先:我使用的是SQL Server Compact,这使得SQL非常严格。
我有两张桌子,他们之间有多对多关系:房间和课程。从房间列表中我想检查房间是否在指定的时间范围内无人居住,这个房间现在有什么课程,这个房间的下一个课程是什么。前两部分没问题:
SELECT a.Id, COUNT(c.Id) AS ConflictingCourses, d.Id AS CurrentCourseId
FROM Rooms AS a
LEFT OUTER JOIN RoomCourses AS b ON b.RoomId = a.Id
-- Conflicting Courses
LEFT OUTER JOIN Courses AS c ON c.Id = b.CourseId AND @startTime <= c.EndTime AND @endTime >= c.StartTime
-- Current Course
LEFT OUTER JOIN Courses AS d ON d.Id = b.CourseId AND @now <= d.EndTime AND @now >= d.StartTime
WHERE (a.Id IN (1,2,3,4))
GROUP BY a.RoomId, d.Id
现在问题:我想要获得第一个具有StartTime的课程。为了学习这门课程,我尝试加入所有课程。从这个结果我认为下一个课程很容易,因为对于每个小组,它是具有较小日期的行的ID:
SELECT a.Id, COUNT(c.Id) AS ConflictingCourses, d.Id AS CurrentCourseId
FROM Rooms AS a
LEFT OUTER JOIN RoomCourses AS b ON b.RoomId = a.Id
-- Conflicting Courses
LEFT OUTER JOIN Courses AS c ON c.Id = b.CourseId AND @startTime <= c.EndTime AND @endTime >= c.StartTime
-- Current Course
LEFT OUTER JOIN Courses AS d ON d.Id = b.CourseId AND @now <= d.EndTime AND @now >= d.StartTime
-- All Upcoming Courses
LEFT OUTER JOIN Courses AS e ON e.Id = b.CourseId AND e.StartTime >= @now
WHERE (a.Id IN (1,2,3,4))
GROUP BY a.RoomId, d.Id
但是我只能使用MIN(e.StartTime)获得下一个课程的startTime。但是我想要MIN(e.StartTime)所属的行的Id。我尝试了数百种组合,变通方法和其他东西,只是为了获得即将上课的ID。主要问题是SQL CE不支持返回标量值的subquerys,因此我无法接收任何允许我只获得下一个课程的信息。
我有什么想法可以获得即将到来的房间课程吗?
答案 0 :(得分:0)
您是否尝试过以下操作?
SELECT a.Id, COUNT(c.Id) AS ConflictingCourses, d.Id AS CurrentCourseId
FROM Rooms AS a
LEFT OUTER JOIN RoomCourses AS b ON b.RoomId = a.Id
-- Conflicting Courses
LEFT OUTER JOIN Courses AS c ON c.Id = b.CourseId AND @startTime <= c.EndTime AND @endTime >= c.StartTime
-- Current Course
LEFT OUTER JOIN Courses AS d ON d.Id = b.CourseId AND @now <= d.EndTime AND @now >= d.StartTime
-- All Upcoming Courses
LEFT OUTER JOIN Courses AS e ON e.Id IN (SELECT MIN(Id)
FROM Courses
WHERE Id = b.CourseId
AND e.StartTime >= @now)
WHERE (a.Id IN (1,2,3,4))
GROUP BY a.RoomId, d.Id
我知道IN在这里没用,因为查询总是只返回1个结果,但它显然是这种情况的解决方法(SQL CE)。