Swamy
Swamy

Reputation: 463

Order by one column and then by another column

I have an SQL Fiddle and the table looks like below

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    

I want to order it by DepartureDate, DepartureTime and BookingRef however related BookingRef should be partitioned together So the above result should look like

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

Upvotes: 0

Views: 37

Answers (2)

Rich Benner
Rich Benner

Reputation: 8113

I'd use a subquery to do your ordering, something like this;

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

Which gives the output that you've shown. See it in the fiddle here

This is going to order by the minimum DepartureTime for each BookingRef.

Upvotes: 1

Brian McAuliffe
Brian McAuliffe

Reputation: 2165

You want to 'Group By'

SELECT column_names FROM table_name WHERE condition GROUP BY BookingRef ORDER BY column_name;

Upvotes: 0

Related Questions