2017-09-01 127 views
0

不同的表,我有我的MySQL数据库三个不同的表:连接三个MySQL数据库

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包含(月明智)的经销商明智salses代表销售业绩数据。 tbl_mas_customer包含销售代表到经销商的映射。一个销售代表有许多经销商。所以我们可以通过映射这两个表来获得特定的销售代表matgrp智能qty_ach。 tbl_matgrp_target包含每个销售代表的matgrp明智目标数量(tar_qty)。它在特定的月份是不变的。每个月他们被分配一个目标。

我知道如何内部联接tbl_mas_customertbl_sales表并获得特定销售代表的matgrp明智当月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 

输出....

matgrp qty_ach 
FG0002 4522 
FG0001 1574 
FG0004 1409 
FG0010 1176 
FG0009 1133 
FG0005 568 
FG0012 65 
FG0017 64 

现在我想的是获得该特定销售代表的目标数量(tar_qty)也为相同的查询。

输出....

matgrp qty_ach tar_qty 
FG0002 4522  3786 
FG0001 1574  990 
FG0004 1409  1320 
FG0010 1176  1858 
FG0009 1133  857 
FG0005 568  457 

回答

1

你需要加入有关系的东西全部三个表像下面

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 
+0

它给了我一个错误的数字。我不想在tar_qty上做一个总和(tar_qty)。因为每个代表每个代表都获得一个特定的matgrp的常量值,并且这个也不会在特定的月份显示我正确的qty_ach –

+0

删除tar_qty的总数并按月添加组 – Naincy

+0

tar_qty为所有matgrp获取相同的值 –