连接2个表的准确结果

时间:2017-04-25 20:36:42

标签: mysql

表A列出了一个项目以及必须通过4个可能站点的每个站点的数量。

Double.parse()

表B列出了通过每个站点处理的件数。

Item      To Cut      To Paste      To Laminate      To Ship
Box          9            9              5              9
Cart         1            0              10             10

当我加入他们时,它会显示:

Item      Cut Done      Paste Done      Laminated      Shipped
Box          9            0                0             0
Box          0            9                0             0
Box          0            0                5             0
Box          0            0                0             9

这是因为表B的工作方式。如何让它在一个表中准确显示总切割和切割完成百分比是否正确?

我的查询是:

Item      To Cut      Cut Done      To Paste      Paste Done
Box          36          9             36             9

1 个答案:

答案 0 :(得分:1)

您应该添加带有计算总和的子查询。

select tableA.Item, To_Cut, To_Paste, To_Laminate, To_Ship, d.Cut_Done, d.Paste_Done, d.Laminated, d.Shipped
from tableA 
inner join (select Item, 
                   sum(Cut_Done) as Cut_Done,
                   sum(Paste_Done) as Paste_Done,
                   sum(Laminated) as Laminated,
                   sum(Shipped) as Shipped
            from   tableB
            group by Item) d
on tableA.Item = d.Item;

| Item | To_Cut | To_Paste | To_Laminate | To_Ship | Cut_Done | Paste_Done | Laminated | Shipped |
|-----:|--------|----------|-------------|---------|----------|------------|-----------|---------|
| Box  | 9      | 9        | 5           | 9       | 9        | 9          | 5         | 0       |

Rextester here