查询是从连接表中选择计数

时间:2017-07-18 15:27:18

标签: mysql

我有货运表和货件明细表。货物通常装有多个纸箱。我正在尝试选择货件表的计数,并从详细信息表中汇总数量。但我的值是从联合表中选出的。

离。 count = 7,当我的货件表中的数量应为4时

 SELECT ss.tenant_id,
 ss.order_id,
 COUNT(ss.shipment_number),
 SUM(sd.qty_shipped)
 FROM shipment ss
     LEFT JOIN detail sd
         ON ss.id = sd.shipment_id
 GROUP BY
     ss.order_id,
     ss.tenant_id;

输出 - >

tenant_id | order_id | count | sum  
-----------+----------+-------+------
        1 |     2573 |     7 | 1350

数据集 - >

shipment
 id  | shipment_number | shipment_status | tracking_number | shipping_cost  
------+-----------------+----------------+----------------+---------------
8332 | 1000048         | confirmed       | 123            | 10.00                    

8333 | 1000049         | confirmed       | 123            | 10.00                   

8334 | 1000050         | confirmed       | 123            | 10.00                  

8335 | 1000051         | confirmed       | 123            | 10.00 


detail
  id   | carton_number | qty_shipped | order_id | shipment_id 
-------+---------------+-------------+----------+------------
 14654 | 1             |         200 |     2573 | 8332 
 14655 | 2             |         200 |     2573 | 8332 
 14656 | 1             |         200 |     2573 | 8333 
 14657 | 1             |         200 |     2573 | 8334 
 14658 | 2             |         200 |     2573 | 8334 
 14659 | 1             |         150 |     2573 | 8335 
 14660 | 2             |         200 |     2573 | 8335 

1 个答案:

答案 0 :(得分:0)

我必须在我的计数中添加明显的内容。

                select ss.tenant_id,
                ss.order_id,
                count(distinct ss.shipment_number),
                sum(sd.qty_shipped)
                from shipping_shipment ss
                    left join shipping_shipmentdetail sd
                        on ss.id = sd.shipment_id
                GROUP BY
                    ss.order_id,
                    ss.tenant_id;