Mysql
 sql >> Base de Dados >  >> RDS >> Mysql

MySQL calcula a porcentagem de duas outras somas calculadas, incluindo um grupo por mês


Use agregação condicional. Não está claro se você quer olhar para os últimos 12/24 meses, ou para os meses de 2017 e os mesmos meses de 2016. Também não entendo como você quer calcular um percentual. Divido os lucros deste ano pelos do ano passado na consulta abaixo. Ajuste isso para que atenda às suas necessidades.
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;