I have three different tables in my MYSQL db:
tbl_sales
company customer ds material matgrp date qty_ach
2100 30000002 21 2000012 FG0001 2015-08-10 42
2100 30000002 21 2000013 FG0002 2015-08-08 21
2200 30000003 21 2000013 FG0002 2015-08-25 21
2400 30000003 21 2000014 FG0001 2015-08-05 22
2100 30000003 21 2000015 FG0001 2015-08-15 15
2300 30000002 21 2000015 FG0003 2015-08-24 21
2100 30000004 21 2000016 FG0003 2016-08-05 16
2100 30000004 21 2000017 FG0003 2016-08-16 32
tbl_mas_customer
customer rep name
30000001 501 Alcon Traders
30000002 501 Ajith Tyre Traders
30000003 501 *AUTO EQUIPMENT TRADING COMPAN
30000004 501 Appolo Tyre Centre
30000005 501 Aitken Spence Travels Ltd
tbl_matgrp_target
rep date matgrp tar_qty
501 2017-08-01 FG0001 990
501 2017-08-01 FG0002 3786
501 2017-08-01 FG0004 1320
501 2017-08-01 FG0005 457
501 2017-08-01 FG0006 75
501 2017-08-01 FG0007 47
501 2017-08-01 FG0008 19
501 2017-08-01 FG0009 857
501 2017-08-01 FG0010 1858
501 2017-08-01 FG0011 356
tbl_sales contains data of dealer wise salses reps' sales achievements(month wise). tbl_mas_customer contains the mapping of the sales rep to the dealer. one sales rep has many dealers. so we can get particular sales rep's matgrp wise qty_ach by mapping those two table. tbl_matgrp_target contains each sales reps' matgrp wise target quantity(tar_qty). it is constant for a particular month. each month they are assigned a target.
i know how to inner join tbl_mas_customer and tbl_sales tables and get particular sales rep's matgrp wise current month qty_ach.
select matgrp, sum(qty_ach) as qty_ach
from tbl_sales
inner join tbl_mas_customer on tbl_sales.customer = tbl_mas_customer.customer
where MONTH(`date`)=MONTH(NOW()) and YEAR(`date`)=YEAR(NOW())
and rep = '501' group by matgrp ORDER BY qty_ach DESC
output....
matgrp qty_ach
FG0002 4522
FG0001 1574
FG0004 1409
FG0010 1176
FG0009 1133
FG0005 568
FG0012 65
FG0017 64
now what i want is to get that particular sales rep's target quantity(tar_qty) also for the same query.
output....
matgrp qty_ach tar_qty
FG0002 4522 3786
FG0001 1574 990
FG0004 1409 1320
FG0010 1176 1858
FG0009 1133 857
FG0005 568 457
You need to join all three tables with relation something like below
select matgrp, sum(qty_ach) as qty_ach, sum(tar_qty) as tar_qty
from tbl_sales ts
inner join tbl_mas_customer on ts.customer = tbl_mas_customer.customer
JOIN tbl_matgrp_target ON tbl_mas_customer.rep = tbl_matgrp_target.rep
where MONTH(ts.`date`)=MONTH(NOW()) and YEAR(ts.`date`)=YEAR(NOW())
and tbl_mas_customer.rep = '501' group by ts.matgrp ORDER BY ts.qty_ach DESC
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.