查询所有关联记录的属性值X

时间:2018-12-11 17:44:37

标签: postgresql relational-division

我有一个查询,它计算关联记录和关联状态

SELECT
  orders.id,
  SUM(CASE WHEN s.shipment_status='CLOSED' THEN 1 ELSE 0 END) as closed,
  COUNT(*) as shipment_count
FROM orders as po
JOIN shipments as s ON s.order_id = po.id 
GROUP BY po.id

我正在尝试查询所有订单,其中全部CLOSED

本质上看上面的内容,只是在closed = shipment_count时返回。

如果我在联接中添加AND子句,那么它将仅限制发货数量。

1 个答案:

答案 0 :(得分:1)

我通过HAVING子句解决了这个问题,该子句不使用select属性。

SELECT
  orders.id
FROM orders as po
JOIN shipments as s ON s.order_id = po.id
GROUP BY po.id
HAVING SUM(CASE WHEN s.shipment_status='CLOSED' THEN 1 ELSE 0 END) = COUNT(*)

不要回答我的问题,以免对他人有所帮助。也许可以从社区获得更好的答案。