简体   繁体   中英

Mysql subtract two row values from group by

I am using the following query to get the results as two rows for earnings and deductions.

select t2.type
     , sum(t1.amount) as total_earnings 
  from employee_pay_elements t1
  join pay_elements t2 
    on (t1.pay_element_id = t2.id)
 group 
    by t2.type

and the result

在此处输入图片说明

Now I need to get the difference (EARNING - DEDUCTION) how do I get the diff easily and efficiently?

Thank you in advance

You can use conditional aggregation:

select sum(case when pe.type = 'EARNING' then epe.amount
                when pe.type = 'DEDUCTION' then - epe.amount
            end) as total_earnings
from employee_pay_elements epe join
     pay_elements pe
     on epe.pay_element_id = pe.id;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM