SQL Server ORDER BY/WHERE with nested select

Posted by Echilon on Stack Overflow See other posts from Stack Overflow or by Echilon
Published on 2010-04-02T14:34:09Z Indexed on 2010/04/02 14:43 UTC
Read the original article Hit count: 311

Filed under:
|
|
|

I'm trying to get SQL Server to order by a column from a nested select. I know this isn't the best way of doing this but it needs to be done.

I have two tables, Bookings and BookingItems. BookingItems contains StartDate and EndDate fields, and there can be multiple BookingItems on a Booking. I need to find the earliest startdate and latest end date from BookingItems, then filter and sort by these values.

I've tried with a nested select, but when I try to use one of the selected columns in a WHERE or ORDER BY, I get an "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 SQL ordering? I'm using SQL Server 2008.

© Stack Overflow or respective owner

Related posts about sql-server-2008

Related posts about sql