sql >> Base de Datos >  >> RDS >> Mysql

MySQL calcula el porcentaje de otras dos sumas calculadas, incluido un grupo por mes

Utilice la agregación condicional. No está claro si quieres mirar los últimos 12/24 meses, o los meses de 2017 y los mismos meses de 2016. Tampoco entiendo cómo quieres calcular un porcentaje. Divido las ganancias de este año por las del año pasado en la siguiente consulta. Ajústalo para que se adapte a tus necesidades.

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;