簡體   English   中英

在MySQL數據庫中連接三個不同的表

[英]Connect three different tables in MySQL database

我的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包含經銷商明智的工資代表的銷售業績(每月明智)的數據。 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

您需要將所有三個表連接起來,如下所示

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM