2016-11-30 4 views
0

Ich muss ein SQL-Skript schreiben, das alle Menschen Client, deren maximales Einkommen zweimal größer, als Mindesteinkommen insgesamt zeigen muss.SQL-Fehler: Betrieb

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 '%ВИЧ' - es ist für Männer in ihren mittleren Namen (russischer Sprache requirments)

Hier ist die Sortierung, wie Tabelle wie folgt aussieht:

enter image description here

A empfängt solche Fehler:

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

Was mache ich falsch?

+0

Warum SELECT DISTINCT? Die GROUP BY gibt keine Duplikate zurück. – jarlh

Antwort

2

anstelle von income_ratio schreiben in Having-Klausel als max(monthly_income_amt)/min(monthly_income_amt)>2.

Auch distinct macht keinen Sinn, da Sie gruppieren.

1

Benötigen Sie Änderungen in Ihrer having-Klausel wie unten.

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

Umschließen Sie die Abfrage in einer abgeleiteten Tabelle. Dann können Sie in der WHERE-Klausel income_ratio setzen:

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;