【问题标题】:Connect three different tables in MySQL database连接 MySQL 数据库中的三个不同的表
【发布时间】:2017-09-01 18:46:18
【问题描述】:

我的 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

【问题讨论】:

    标签: php mysql


    【解决方案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
    

    【讨论】:

    • 它给了我一个错误的数字。我不想对 tar_qty 进行求和(tar_qty)。因为每个月每个代表都会获得特定 matgrp 的恒定值,而这个也没有向我显示特定月份的正确 qty_ach
    • 删除 tar_qty 的总和并按月份添加分组
    • tar_qty 为所有 matgrp 获得相同的值
    猜你喜欢
    • 2013-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-14
    • 2012-11-23
    相关资源
    最近更新 更多