简体   繁体   English

Mysql 从 group by 中减去两行值

[英]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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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