Yii2获得一列的总和

时间:2017-10-21 11:19:29

标签: mysql sql database yii2

我有两张桌子:

  1. warehouse ['id','warehouse_name']
  2. products ['id','product_name','qty','warehouse_id']
  3. 通过warehouse_id连接。

    enter image description here

    enter image description here

    enter image description here

    我需要groupBy product_name和sum列qty和仓库 例如:

    Product 2 14 WH1,WH2

1 个答案:

答案 0 :(得分:0)

查看您的示例输出数据,我认为您正在寻找SUMGROUP_CONCAT

SELECT p.product_name,
       sum(p.qty) AS qty,
       GROUP_CONCAT(w.warehouse_name
                    ORDER BY w.warehouse_name ASC SEPARATOR ',') AS warehouse
FROM product p
INNER JOIN warehouse w ON p.warehouse_id = w.id
GROUP BY p.product_name;

<强>结果:

product_name    qty     warehouse
------------    ---     ---------
product 2        14     WH1,WH2
product 3        2      WH1
product 5        4      WH3

<强> DEMO