I am trying to get SQL Server to order by column from a nested select. I know that this is not the best way to do this, but it needs to be done.
I have two tables, Reservation and Reservation. BookingItems has StartDate and EndDate fields, and there may be several reservations when booking. I need to find the earliest start date and last end date using BookItems, then filter and sort by these values.
I tried with a nested select, but when I try to use one of the selected columns in WHERE or ORDER BY, I get "Invalid column name".
SELECT b.*, (SELECT COUNT(*) FROM bookingitems i WHERE b.BookingID = i.BookingID) AS TotalRooms,
(SELECT MIN(i.StartDate) FROM bookingitems i WHERE b.BookingID = i.BookingID) AS StartDate,
(SELECT MAX(i.EndDate) FROM bookingitems i WHERE b.BookingID = i.BookingID) AS EndDate
FROM bookings b LEFT JOIN customers c ON b.CustomerID = c.CustomerID WHERE StartDate >= '2010-01-01'
Am I missing something about ordering SQL? I am using SQL Server 2008.