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

Consulta SQL com união e junção


Use a seguinte 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'

A cláusula group by não é necessária para as consultas internas, pois não há função de grupo. Eu o movi para a consulta mais externa