SUM使用别名和group by选择列

时间:2016-05-13 15:17:15

标签: mysql

我正在尝试使用别名和分组依据对选择列执行计算。查询如下(来自之前的问题):

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

我已经尝试将其置于另一笔总和中,但结果相同。

1 个答案:

答案 0 :(得分:0)

我是愚蠢的,我在单个蜱中引用了别名,这就是为什么它没有计算。解决方案:

UIContainerView