gpt4 book ai didi

MySQL计算其他两个计算总和(包括按月分组)的百分比

转载 作者:行者123 更新时间:2023-11-29 17:51:54 24 4
gpt4 key购买 nike

假设我有 3 个带有这样模型的 table

enter image description here

我想要的结果现在看起来像这样

enter image description here

我想计算所有员工每月的营业额和利润,并将其与去年同月进行比较,并计算利润百分比的差异。它应该包括过去 12 个月的 INTERVAL 函数。

select
bookings.b_emp_id as "Employee",
MONTH(bookings.b_date) as Month,
@turnover1 := sum(bookings.b_turnover) as '2017-turnover',
@turnover2 := (select sum(lx.b_turnover)
from bookings as lx
where lx.b_date = date_add(bookings.b_date, INTERVAL -1 YEAR)
GROUP BY
MONTH(bookings.b_date),
YEAR(bookings.b_date),
bookings.b_emp_id
) as '2016-turnover',
sum(b_profit) as '2017-profit',
@profit1 := (select sum(lx.umsatz_fees)
from bookings as lx
where lx.b_date = date_add(bookings.b_date,INTERVAL -1 YEAR)
GROUP BY
MONTH(bookings.b_date),
YEAR(bookings.b_date),
bookings.b_emp_id
) as '2016-profit'
from bookings
where bookings.b_date > '2017-01-01'
and bookings.b_emp_id = ´SA´
GROUP BY MONTH(bookings.b_date)
order by bookings.b_date desc

最佳答案

使用条件聚合。目前尚不清楚您是否想查看过去 12/24 个月,还是 2017 年的月份和 2016 年的同一月份。我也不明白您想如何计算百分比。我在下面的查询中将今年的利润除以去年的利润。调整此项以满足您的需求。

select
b_emp_id,
month,
turnover_this_year,
profit_this_year,
turnover_last_year,
profit_last_year,
profit_this_year / profit_last_year * 100 as diff
from
(
select
b_emp_id,
month(b_date) as month,
sum(case when year(b_date) = year(curdate()) then b_turnover end) as turnover_this_year,
sum(case when year(b_date) = year(curdate()) then b_profit end) as profit_this_year,
sum(case when year(b_date) < year(curdate()) then b_turnover end) as turnover_last_year,
sum(case when year(b_date) < year(curdate()) then b_profit end) as profit_last_year
from bookings
where year(b_date) in (year(curdate()), year(curdate()) - 1)
and month(b_date) <= month(curdate())
group by b_emp_id, month(b_date)
) figures
order by b_emp_id, month;

关于MySQL计算其他两个计算总和(包括按月分组)的百分比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49249660/

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