1

I need to use the value obtained from SEATS_RESERVED like so. The query below gives me an Invalid column name 'SEATS_RESERVED' error.

SELECT *,
SEATS_RESERVED =
(SELECT COUNT(UID)
FROM person WHERE person.RES_DATE = reservation_dates.RES_DATE 
AND person.ARCHIVE = 'FALSE')
FROM reservation_dates
WHERE TERM = ?
AND SEATS_RESERVED < MAX_SEATS;
1
  • if SEATS_RESERVED is a variable declare it with@. for example: @SEATS_RESERVED Commented Feb 14, 2012 at 15:10

2 Answers 2

4

You can't create a derived field in the SELECT and reference it in the WHERE clause.

There are several options to deal with that, here is one with the least changes to your query.

SELECT * FROM
(
  SELECT *,
  SEATS_RESERVED =
  (SELECT COUNT(UID)
  FROM person WHERE person.RES_DATE = reservation_dates.RES_DATE 
  AND person.ARCHIVE = 'FALSE')
  FROM reservation_dates
  WHERE TERM = ?
)
  AS data
WHERE SEATS_RESERVED < MAX_SEATS;
Sign up to request clarification or add additional context in comments.

Comments

-1

You're trying to set SEATS_RESERVED equal to a value in your subquery, but you haven't declared SEATS_RESERVED yet. Also, where is MAX_SEATS defined?

How about this:

DECLARE @MAX_SEATS INT
SET @MAX_SEATS = <some integer>


SELECT *,
   (SELECT COUNT(UID) FROM person WHERE person.RES_DATE = reservation_dates.RES_DATE 
AND person.ARCHIVE = 'FALSE' HAVING COUNT(UID) < @MAX_SEATS;) AS SEATS_RESERVED
FROM reservation_dates
WHERE TERM = ?

1 Comment

It's not a variable. It's an alternative syntaxt to SELECT *, (sub-query) AS SEATS_RESERVED FROM .... And is appears that MAX_SEATS is a field in the reservation_dates table.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.