2016-05-08 49 views
0

我的查詢:如何在postgres中選擇一列?

select c.id, sum(case when r.paid_out>='1' then 0 else 1 end) as all_paids 
from people p1, houses h, policies p2, receipts r 
where p1.id = h.id 
and h.code = p2.code 
and p2.code_policy = r.code_policy 
group by p1.id 
having all_paids= 0; 

Postesql回到我下面的錯誤:

錯誤:沒有列 'all_paids'

我已經試過幾件事,但沒有任何幫助表示讚賞

回答

4

首先,學習使用正確的join語法。

其次,你可以使用表達式爲having子句或子查詢:

select p1.id 
from people p1 join 
    houses h 
    on p1.id = h.id join 
    policies p2 
    on h.code = p2.code join 
    receipts r 
    on p2.code_policy = r.code_policy 
group by p1.id 
having sum(case when r.paid_out >= '1' then 0 else 1 end) = 0; 

注:沒有定義c.id,所以我承擔select應根據group byp1.id

我應該說,這個邏輯會經常使用not exists表示:

select p1.* 
from people p1 
where not exists (select 1 
        from houses h 
         policies p2 
         on h.code = p2.code join 
         receipts r 
         on p2.code_policy = r.code_policy 
        where p1.id = h.id and 
         r.paid_out >= '1' 
       ); 

這消除了聚集。