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

Consulta SQL con union y join

Utilice la siguiente consulta

select `company_name, `store_name`, MONTH, sum(`sales`) as sales, sum(purchase) as purchase   from (
select `company_group`.`company_name, `store`.`store_name`, MONTHNAME(date) AS MONTH,`sales`.`sales` , 0 as purchase
from company_group, store,sales
where `company_group`.`company.id`=`sales`.`company.id`
and `store`.`store.id`=`sales`.`store.id`

UNION

select `company_group`.`company_name, `store`.`store_name`, MONTHNAME(date) AS MONTH,`wh_sales`.`sales`, 0 as purchase
from company_group, store,wh_sales
where `company_group`.`company.id`=`wh_sales`.`company.id`
and `store`.`store.id`=`wh_sales`.`store.id`

UNION

select `company_group`.`company_name, `store`.`store_name`, MONTHNAME(date) AS MONTH, 0 as sales, purchase
from company_group, store,purchase
where `company_group`.`company.id`=`purchase`.`company.id`
and `store`.`store.id`=`purchase`.`store.id`) a
group by company_name,store_name, 'MONTH'

La cláusula group by no es necesaria para las consultas internas ya que no hay una función de grupo. Lo he movido a la consulta más externa