我有一个查询,它计算关联记录和关联状态
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
子句,那么它将仅限制发货数量。
答案 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(*)
不要回答我的问题,以免对他人有所帮助。也许可以从社区获得更好的答案。