postgresql - 如何在 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 |
解决方案
要获得所需的结果,请使用以下查询:
SELECT shipment_id, sum(no_of_boxes), sum(no_of_pallets)
FROM shipments
GROUP BY shipment_id;
推荐阅读
- reactjs - 如何在功能组件中映射设置器?
- c# - 当涉及外键时,无法邮递员 POST 到 dot net API c#
- javascript - firebase-messaging-sw.js 文件中用于 firebase 应用程序初始化的动态凭据
- java - 如何使用 Spring Data Redis 2.x 通过 Spring Boot 从 redis 缓存中获取所有密钥?
- python - 使用 Python 和 Kivy 的小型纸牌游戏
- python - 清除 vlc media_list_player 的媒体列表将不允许重新启动媒体播放器
- c - C OMP for 并行区域中的循环。非工作共享
- javascript - 如何在另一个简单的网页中添加我的 Angular 应用程序?
- r - ggplot上的双轴,更新左侧轴
- javascript - React native 传播不可迭代实例的无效尝试