2016-05-13 154 views
-3

我試圖對使用別名和分組方式的選擇列執行計算。查詢低於(在從之前的行問題):SUM使用別名和組選擇列

select r.res_id, 
    r.arrive_date, 
    r.depart_date, 
    r.res_type, 
    if(DATEDIFF(r.depart_date, r.arrive_date) >29, 'LT', 'ST') as 'StayType', 
    SUM(r.rent + r.fee_arr_early + r.fee_dep_late + r.fee_peace_waiver + r.fee_pool + r.city_tax + r.fee_cleaning + r.fee_pet + r.fee_tshirt + r.fee_misc + r.fee_non_tax + r.fee_processing + r.fee_travel_ins + r.fee_event + r.fee_cancel) as 'folioTotal', 
    coalesce((select SUM(g.amount) from guest_payments as g where g.resId = r.res_id and charge_type = 'charge' and approved = 'Y'),0) as 'payments', 
    coalesce((select SUM(g.amount) from guest_payments as g where g.resId = r.res_id and charge_type = 'credit' and approved = 'Y'),0) as 'credits', 
    (SUM('folioTotal') - SUM('payments') + SUM('credits')) as 'folioBalance' 
from reservations as r 
    join guest_payments as g 
     on r.res_id = g.resId 
     group by r.res_id 

我試過把這個內部的另一個總和與相同的結果。

+0

您是否嘗試使用sum()的sum()而不是sum()作爲folioTotal的總和字段? – Serge

+0

問題是什麼?向我們展示你的表格。 –

+0

如果您願意,請考慮遵循以下簡單的兩步操作步驟:1.如果您尚未這樣做,請提供適當的CREATE和INSERT語句(和/或sqlfiddle),以便我們可以更輕鬆地複製問題。 2.如果您尚未這樣做,請提供與步驟1中提供的信息相對應的所需結果集。 – Strawberry

回答

0

我當時很愚蠢,我在單蜱裏面引用別名,這就是爲什麼它沒有計算。解決方案:

select r.res_id, 
    r.arrive_date, 
    r.depart_date, 
    r.res_type, 
    g.entry_date, 
    if(DATEDIFF(r.depart_date, r.arrive_date) >29, 'LT', 'ST') as 'StayType', 
    (select SUM(r.rent + r.fee_arr_early + r.fee_dep_late + r.fee_peace_waiver + r.fee_pool + r.city_tax + r.fee_cleaning + r.fee_pet + r.fee_tshirt + r.fee_misc + r.fee_non_tax + r.fee_processing + r.fee_travel_ins + r.fee_event + r.fee_cancel) from reservations as r where r.res_id = g.resId) as 'folioTotal', 
    coalesce((select SUM(g.amount) from guest_payments as g where g.resId = r.res_id and charge_type = 'charge'),0) as 'payments', 
    coalesce((select SUM(g.amount)* -1 from guest_payments as g where g.resId = r.res_id and charge_type = 'credit' and approved = 'Y'),0) as 'credits', 
    (select folioTotal - payments + credits) 
from reservations as r 
    join guest_payments as g 
     on r.res_id = g.resId 
     group by r.res_id