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

标签 mysql sql

假设我有 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/

相关文章:

java - 是否有一个支持 fetchSize 的 mysql JDBC?

mysql - 分组依据不返回空值

mysql - 插入带有自动增量列的 MySQL 表

MYSQL::从没有最新行的表中选择行

php - Angularjs如何获取服务中$http响应返回的Json格式的解析数据

Mysql存储过程

sql - INSERT INTO over linked server MS SQL -> MySQL 的第一列总是空字符串

php - 你能在 SQL 案例中使用 php 吗?

sql server 从 XML 列获取特定数据

SQL 服务器 : delete where string value contains another value