2016-11-30 20 views
0

我需要编写一个sql脚本,它必须显示所有man客户端,其最大收入是最小收入的两倍。SQL错误:有操作

SELECT 
    DISTINCT 
    customer_rk, 
    max(monthly_income_amt), 
    min(monthly_income_amt), 
    max(monthly_income_amt)/min(monthly_income_amt) AS income_ratio 
FROM asql.individual_customer 
WHERE middle_nm LIKE '%ВИЧ' 
GROUP BY customer_rk 
HAVING income_ratio > 2; 

middle_nm like '%ВИЧ' - 这是由他们的中间名排序男人(俄语质量要求)

下面是桌子的样子:

enter image description here

A收到这样的错误:

ERROR: column "income_ratio" does not exist (line 6)

我做错了什么?

+0

为什么选择DISTINCT? GROUP BY不返回重复项。 – jarlh

回答

2

而不是income_ratio写入子句为max(monthly_income_amt)/min(monthly_income_amt)>2

另外distinct没有意义,因为你是分组。

1

需要修改你的条款如下。

SELECT 
     DISTINCT 
     customer_rk, 
     max(monthly_income_amt), 
     min(monthly_income_amt), 
     max(monthly_income_amt)/min(monthly_income_amt) AS income_ratio 
    FROM asql.individual_customer 
    WHERE middle_nm LIKE '%ВИЧ' 
    GROUP BY customer_rk 
    HAVING (max(monthly_income_amt)/min(monthly_income_amt)) > 2 
0

将查询包装在派生表中。然后,您可以将income_ratio放在WHERE子句中:

select * from 
(
    SELECT 
     customer_rk, 
     max(monthly_income_amt), 
     min(monthly_income_amt), 
     max(monthly_income_amt)/min(monthly_income_amt) AS income_ratio 
    FROM asql.individual_customer 
    WHERE middle_nm LIKE '%ВИЧ' 
    GROUP BY customer_rk 
) dt 
where income__ratio > 2;