首页 > 解决方案 > 如何在 PostgreSQL 中获取计数派生列的总和?

问题描述

我有一个带有 shipping_id、no_of_boxes 和 no_of_pallets 的表,如下所示。

装运编号 no_of_boxes no_of_pallets
1 23 0
1 45 0
1 0 1
2 3 0
2 165 0
2 0 10

我想将 no_of_boxes 和 no_of_pallets 列与它们各自的 shipping_id 相加。no_of_boxes 和 no_of_pallets 列是 COUNT 派生列(通过 JOINS 从不同的表计算得出)。

我尝试为此编写子查询,但没有帮助。下面的子查询是针对 no_of_boxes 的,类似的查询是针对 no_of_pallets 编写的。

SELECT SUM(no_of_boxes)
FROM   (SELECT COUNT(si.shipment_item_id) AS no_of_boxes
        FROM   shipment_item AS si
               JOIN shipment_item AS si
                 ON si.shipment_order_systemid = sho.system_id
               JOIN shipping_unit AS su
                 ON su.system_id = si.shipping_unit_systemid
        WHERE  su.unit LIKE 'BOX'
        GROUP  BY si.shipment_item_id,
                  su.unit) t 

我想要的结果是:

装运编号 no_of_boxes no_of_pallets
1 68 1
2 168 10

标签: postgresql

解决方案


要获得所需的结果,请使用以下查询:

SELECT shipment_id, sum(no_of_boxes), sum(no_of_pallets)
FROM shipments
GROUP BY shipment_id;

推荐阅读