如何在WHERE子句中引用列别名

时间:2020-05-02 11:20:38

标签: sql oracle

我想将别名(其中有空格)与WHERE子句中的空格进行比较。

select r.resortid, sum(b.adultcount+b.childcount) as "Total Guest"
from   resort r, booking b
where  r.resortid = b.resortid and "Total Guest" <= 10
group by r.resortid
order by r.resortid;

我得到的错误是:

where  r.resortid=b.resortid and "Total Guest" <=10
                                 *
ERROR at line 3:
ORA-00904: "Total Guest": invalid identifier

4 个答案:

答案 0 :(得分:3)

使用HAVING子句并使用显式标准JOIN语法,而不要使用逗号分隔:

SELECT r.resortid, SUM(b.adultcount+b.childcount)
FROM resort r INNER JOIN
     booking b
     ON r.resortid = b.resortid 
GROUP BY r.resortid
HAVING SUM(b.adultcount+b.childcount) <= 10;

Where子句仅过滤原始数据,不对数据进行汇总。

答案 1 :(得分:2)

鉴于度假村可能没有预订,我建议您使用left join

select r.resortid, coalesce(sum(b.adultcount + b.childcount), 0) as total_guests
from resort r join
     booking b 
     on r.resortid = b.resortid 
group by r.resortid
having coalesce(sum(b.adultcount + b.childcount), 0) <= 10
order by r.resortid;

如果所有度假村都已预订,则join不是必需的:

select b.resortid, sum(b.adultcount + b.childcount) as total_guests
from booking b 
group by b.resortid
having sum(b.adultcount + b.childcount) <= 10
order by r.resortid;

答案 2 :(得分:2)

您不能在同一条sql语句中定义的条件中引用别名。

在Oracle / MariaDB / MySQL数据库中,您有3种可能性:

1)重写计算列,如果它是由聚合函数计算的,则必须将条件放在“ HAVING”子句中:

SELECT r.resortid, sum(b.adultcount+b.childcount) as "Total Guest"
  FROM resort r, booking b
 WHERE r.resortid = b.resortid
 GROUP BY r.resortid
  HAVING sum(b.adultcount+b.childcount) <= 10
ORDER BY r.resortid;

2)使用子查询:

SELECT *
  FROM
    (SELECT r.resortid, sum(b.adultcount+b.childcount) as TotalGuest
      FROM resort r, booking b
     WHERE r.resortid = b.resortid
     GROUP BY r.resortid) AS totalg
 WHERE TotalGuest <= 10
ORDER BY resortid;

3)使用“ WITH”子句编写子查询:

WITH totalg AS
(SELECT r.resortid, sum(b.adultcount+b.childcount) as TotalGuest
  FROM resort r, booking b
 WHERE r.resortid = b.resortid
GROUP BY r.resortid)
SELECT *
  FROM totalg
 WHERE TotalGuest <= 10
ORDER BY resortid;

答案 3 :(得分:0)

Having,而不是where;而且,JOIN不会造成任何伤害。

select r.resortid, 
       sum(b.adultcount + b.childcount) as "Total Guest"
from resort r join booking b on r.resortid = b.resortid 
group by r.resortid
having sum(b.adultcount + b.childcount) <= 10
order by r.resortid;
相关问题