我正在尝试编写一个查询,该查询对处于特定状态的供应商组中的产品数量进行计数,如果没有产品,则返回0。
此查询仅在产品存在时返回计数。
<button id="fuck">click</button>
答案 0 :(得分:1)
使用sum()
而不是count()
,然后使用select case
,这样我们就可以忽略您的where
子句。
SUPPLIER_GROUP_ATTRS = [
"id",
"sum(case when products.state='completed' then 1 else 0 end) as completed_products_count"
]
SupplierGroup.left_joins(:products).select(SUPPLIER_GROUP_ATTRS).group(:id)