我需要使用从SEATS_RESERVED获得的值。下面的查询给我一个无效的列名称'SEATS_RESERVED'错误。
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;
答案 0 :(得分:4)
您无法在SELECT 中创建派生字段,而在WHERE子句中引用它。
有几种方法可以解决这个问题,其中一个选项对查询的更改最少。
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;
答案 1 :(得分:-1)
您尝试将SEATS_RESERVED设置为等于子查询中的值,但尚未声明SEATS_RESERVED。另外,MAX_SEATS定义在哪里?
这个怎么样:
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 = ?