我有SQL Fiddle,表格如下所示
TicketId EmployeeId BookingRef DepartureDate DepartureTime
1 1110341 8662225387 2017-10-16 14:00:00.0000000
2 1110341 8662225388 2017-10-17 14:36:00.0000000
3 1110341 8662225388 2017-10-17 21:39:00.0000000
4 1110341 8662225389 2017-10-12 17:15:00.0000000
5 1110341 8662225390 2017-10-12 18:42:00.0000000
6 1110341 8662225390 2017-10-16 14:15:00.0000000
我想通过DepartureDate,DepartureTime和BookingRef订购,但是相关的BookingRef应该被分区在一起所以上面的结果应该是
TicketId EmployeeId BookingRef DepartureDate DepartureTime
4 1110341 8662225389 2017-10-12 17:15:00.0000000
5 1110341 8662225390 2017-10-12 18:42:00.0000000
6 1110341 8662225390 2017-10-16 14:15:00.0000000
1 1110341 8662225387 2017-10-16 14:00:00.0000000
2 1110341 8662225388 2017-10-17 14:36:00.0000000
3 1110341 8662225388 2017-10-17 21:39:00.0000000
答案 0 :(得分:1)
我会使用子查询来进行排序,就像这样;
SELECT
t.*
FROM Ticket t
JOIN (SELECT BookingRef, MIN(DepartureDate) MinDeparture FROM Ticket GROUP BY BookingRef) sub
ON t.BookingRef = sub.BookingRef
ORDER BY sub.MinDeparture ASC, t.BookingRef ASC
它给出了您显示的输出。在小提琴here
中查看这将按每个BookingRef的最小DepartureTime订购。
答案 1 :(得分:0)
你想'分组'
SELECT column_names FROM table_name WHERE condition GROUP BY BookingRef ORDER BY column_name;