group by - Combining MySQL queries yields incorrect answer -
ok, have lot of sales data each of our clients. have been able find query total volume of sales each sales rep using simple query:
select `merchantaddresses`.`rep number` `rep number`, sum(`residuals_2010_12`.`qual cr vol` + `residuals_2010_12`.`qual ch vol`) `vol_2010_12`, `reps`.`first` `first`, `reps`.`last` `last` `merchantaddresses`, `residuals_2010_12`, `reps` `residuals_2010_12`.`mid` = `merchantaddresses`.`mid` , `reps`.`id` = `merchantaddresses`.`rep number` group `merchantaddresses`.`rep number` order sum(`residuals_2010_12`.`qual cr vol` + `residuals_2010_12`.`qual ch vol`) desc
this code works totally fine, returning table grouping total sales sales rep single month. @ moment, have been running 3 separate queries sales data 3 months. want combine these 3 queries one.
so, did following:
select `merchantaddresses`.`rep number` `rep number`, sum(`residuals_2010_12`.`qual cr vol` + `residuals_2010_12`.`qual ch vol`) `vol_2010_12`, sum(`residuals_2010_11`.`qual cr vol` + `residuals_2010_11`.`qual ch vol`) `vol_2010_11`, sum(`residuals_2010_10`.`qual cr vol` + `residuals_2010_10`.`qual ch vol`) `vol_2010_10`, `reps`.`first` `first`, `reps`.`last` `last` `merchantaddresses`, `residuals_2010_12` join on `residuals_2010_11` join on `residuals_2010_10`, `reps` `residuals_2010_12`.`mid` = `merchantaddresses`.`mid` , `residuals_2010_11`.`mid` = `merchantaddresses`.`mid` , `residuals_2010_10`.`mid` = `merchantaddresses`.`mid` , `reps`.`id` = `merchantaddresses`.`rep number` group `merchantaddresses`.`rep number` order sum(`residuals_2010_12`.`qual cr vol` + `residuals_2010_12`.`qual ch vol`) desc
what have found incorrect values query. works, volume value each sales rep small...
any ideas? thanks!
i think can't join these monthly tables, because not related in way. share same merchant address, that's all.
using union all, can combine results of multiple queries. way can value of monthly records in subquery , sum them in parent.
i took liberty of adding aliasing in queries.
select m.`rep number`, sum(m.vol10) vol_2010_10, sum(m.vol11) vol_2010_11, sum(m.vol12) vol_2010_12, m.first, m.last ( select ma.`rep number`, r10.`qual cr vol` + r10.`qual ch vol` vol10, null vol11, null vol12 merchantaddresses ma inner join residuals_2010_10 r10 on r10.mid = ma.mid union select ma.`rep number`, null vol10, r11.`qual cr vol` + r11.`qual ch vol` vol11, null vol12 merchantaddresses ma inner join residuals_2010_11 r11 on r11.mid = ma.mid union select ma.`rep number`, null vol10, null vol11, r12.`qual cr vol` + r12.`qual ch vol` vol12 merchantaddresses ma inner join residuals_2010_12 r12 on r12.mid = ma.mid ) m inner join reps r on r.id = m.`rep number` group m.`rep number` order sum(m.vol12) desc
Comments
Post a Comment