我正在寻找一种计算布尔值百分比率的解决方案:
型号:
产品1 - < - > n组件
Components.essential是一个布尔属性
我想要计算的是:
SELECT products.*, count(comp_a.essential)/count(comp_b.essential) AS essential_percentage
From products
INNER JOIN components AS comp_a ON products.id = comp_a.product_id
INNER JOIN components AS comp_b ON products.id = comp_b.product_id
WHERE comp_a.essential = 1
GROUP BY products.id
不幸的是,这个语句计算的组件太多,因为组件模型上有两个INNER JOIN ......
对此有何帮助?
马库斯
答案 0 :(得分:3)
只需要一次加入。请注意标准的GROUP BY子句。
这给了" true"百分之因为我认为这是你的意思(不是假的)
SELECT
p.*,
count(CASE WHEN c.essential = 1 THEN 1 END) / count(*) AS essential_percentage
From
products p
LEFT OUTER JOIN
components c ON p.id = c.product_id
GROUP BY
p.*;
或
count(nullif(c.essential, 0)) / count(*) AS essential_percentage