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_customer和tbl_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
它給了我一個錯誤的數字。我不想在tar_qty上做一個總和(tar_qty)。因爲每個代表每個代表都獲得一個特定的matgrp的常量值,並且這個也不會在特定的月份顯示我正確的qty_ach –
刪除tar_qty的總數並按月添加組 – Naincy
tar_qty爲所有matgrp獲取相同的值 –