gpt4 book ai didi

Mysql从group by中减去两行值

转载 作者:行者123 更新时间:2023-11-29 09:28:28 26 4
gpt4 key购买 nike

我使用以下查询来获取两行收入和扣除额的结果。

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

和结果

enter image description here

现在我需要获取差异(收入 - 扣除),如何轻松高效地获取差异?

提前谢谢

最佳答案

您可以使用条件聚合:

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;

关于Mysql从group by中减去两行值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59198936/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com