如何从MySQL中的不同表分组?

时间:2017-03-24 06:46:24

标签: mysql group-by subquery

表A具有ID和UnitCost列

    ID           UnitCost
    1            10.00
    2            5.00
    3            1.00

表B具有LotID和ID,它是表A的外键

    LotID         ID From Table A
    A1            1
    A2            1
    A2            2
    A2            2
    A3            3

期望的输出:

    LotID         Total
    A1            10.00
    A2            20.00
    A3            1.00

2 个答案:

答案 0 :(得分:0)

使用GROUP BY,然后总结单位成本值。这是查询:

SELECT b.LotID, SUM(a.UnitCost) AS Total
FROM tableA a JOIN tableB b ON a.ID = b.ID
GROUP BY b.LotID

答案 1 :(得分:0)

首先,您需要使用JOIN MYSQL JOIN两个表,然后您需要对LotID进行分组,然后sum将汇总这样的单播值

select table_b.LoatID , sum(table_a.UnitCast) as total 
from table_a join table_b 
on table_a.ID = table_b.ID 
group_by table_b.LotID ;

1)Mysql JOIN Reference

2)Mysql group by