Get the smallest start date for several elements and group them?

时间:2016-07-11 21:45:16

标签: sql sql-server date group-by sql-order-by

I have this table called "Class". Class has Class ID, Room ID, and Class Start Time.

For example:

Class_ID: 1

Room_ID: 1234

Class_Start_Time: 07/11/2016 1 pm

Class_ID: 2

Room_ID: 1234

Class_Start_Time: 07/11/2016 9 am

Class_ID: 4

Room_ID: 1235

Class_Start_Time: 07/11/2016 8 am

I need to get the smallest start time for each room. Meaning that Room 1234 would get 07/11/2016 9 am and Room 1235 would get 07/11/2016 8 am (only one start time). I tried this:

 SELECT   Room_ID
 FROM     Courses
 GROUP BY Room_ID
 ORDER BY Class_Start_Time

It asks me to include the start time in the group by, but if I do so, it would give me all the start times and repeated rooms, when what I need is only one of each room and ordered by the room's respective start time. So...

Room_ID = 1235

Start time =  07/11/2016 8 am

Room_ID = 1234

Start time =  07/11/2016 9 am

The order of the rooms doesn't matter is the order of each smallest start time that does. Any suggestions?

2 个答案:

答案 0 :(得分:1)

You can use the ranking functions in SQL Server such as the Row_Number. You can do some reading here: https://msdn.microsoft.com/en-us/library/ms186734.aspx

I think this is what you are looking for.

Create Table Courses
(
ClassId int null,
Room_Id int null,
Class_Start_Time datetime null
)

Insert into Courses
values ('1','1234','2016-07-11 13:00:00.000')
Insert into Courses
values ('2','1234','2016-07-11 09:00:00.000')
Insert into Courses
values ('4','1235','2016-07-11 08:00:00.000')


Select t.ClassID,t.Room_Id,t.Class_Start_Time from
(
 SELECT *,row_number() over (partition by Room_Id order by Class_Start_Time) as SequenceNumber
 from Courses
 )t
 Where t.SequenceNumber=1
 order by Class_Start_Time

答案 1 :(得分:0)

Use MIN(), give your Class_Start_Time an alias and order by it.

SELECT Room_Id, MIN(Class_Start_Time) Start
FROM Courses
GROUP BY Room_Id
ORDER BY Start