SQL语法问题

时间:2011-03-16 02:21:23

标签: join sql

我正在加入两个表并进行简单计数,但我似乎无法将连接的键变量重命名为更适合两个表的内容,我不断收到错误'“CUSTOMER_NO”在该表中无效它被使用的背景。'我确定这只是一个小的语法错误,但我看不到它......

SELECT owner_no AS customer_no,

CASE
WHEN customer_no BETWEEN 5000 and 5999 THEN 'RENTER'
WHEN customer_no BETWEEN 6000 and 6999 THEN 'OWNER'
END AS customer_type

FROM owner_phone AS op
INNER JOIN renter_phone AS rp ON op.owner_no = rp.renter_no

GROUP BY customer_no
HAVING COUNT(*) > 1;

2 个答案:

答案 0 :(得分:3)

使用CASE和GROUP BY中的实际列名,而不是别名列名。

CASE
WHEN owner_no BETWEEN 5000 and 5999 THEN 'RENTER'
WHEN owner_no BETWEEN 6000 and 6999 THEN 'OWNER'
END AS customer_type

FROM owner_phone AS op
INNER JOIN renter_phone AS rp ON op.owner_no = rp.renter_no
GROUP BY owner_no
HAVING Count(*) > 1;

答案 1 :(得分:2)

您必须在查询的其余部分使用OWNER_NO,但保留AS CUSTOMER_NO以使其成为列名。

SELECT owner_no AS customer_no,
CASE
    WHEN owner_no BETWEEN 5000 and 5999 THEN 'RENTER'
    WHEN owner_no BETWEEN 6000 and 6999 THEN 'OWNER'
END AS customer_type
FROM owner_phone AS op
INNER JOIN renter_phone AS rp ON op.owner_no = rp.renter_no
GROUP BY owner_no 
HAVING COUNT(*) > 1;