我正在尝试检查产品A中的某些功能是否也都包含在产品B中。我们会计算完全满足产品A的所有功能的产品B数量。
我的查询返回Count的正确值,但是,我希望它显示0,其中没有这样的产品B具有产品A的功能。此时,它只返回计数所在的值大于1.
有关进一步说明,请参阅以下代码:
SELECT P1.Product_ID, COUNT(P2.Product_ID) AS NUMBER
FROM Products P1, PRODUCTS P2
WHERE P1.Product_ID != P2.Product_ID
AND
NOT EXISTS (
( SELECT FEATURELIST.feature_id
FROM FEATURELIST
WHERE FEATURELIST.Product_ID = P1.Product_ID)
MINUS
( SELECT FEATURELIST.feature_id
FROM FEATURELIST
WHERE FEATURELIST.Product_ID = P2.Product_ID )
)
GROUP BY P1.PNO;
这会返回如下内容:
Product_ID | NUMBER
1 2
5 7
13 2
17 4
我希望它返回完整的Product_ID列表..所以像这样:
Product_ID | NUMBER
1 2
2 0
3 0
4 0
5 7
6 0
7 0
.. ..
17 4
使用oracle sql。
答案 0 :(得分:2)
一个简单的解决方案可能是UNION
所有默认COUNT
为0的产品,并对结果执行额外的GROUP BY
。
SELECT P1.Product_ID, SUM(NUMBER) AS NUMBER
FROM (
SELECT P1.Product_ID, 0 AS NUMBER
FROM Products P1
UNION ALL
SELECT P1.Product_ID, COUNT(P2.Product_ID) AS NUMBER
FROM Products P1, PRODUCTS P2
WHERE P1.Product_ID != P2.Product_ID
AND NOT EXISTS (
( SELECT FEATURELIST.feature_id
FROM FEATURELIST
WHERE FEATURELIST.Product_ID = P1.Product_ID)
MINUS
( SELECT FEATURELIST.feature_id
FROM FEATURELIST
WHERE FEATURELIST.Product_ID = P2.Product_ID )
)
GROUP BY P1.PNO
) P1
GROUP BY
P1.Product_ID
答案 1 :(得分:2)
SELECT P1.Product_ID, COUNT(P2.Product_ID) AS NUMBER
FROM
Products P1
LEFT JOIN
Products P2
ON P1.Product_ID != P2.Product_ID
AND NOT EXISTS
( ( SELECT FEATURELIST.feature_id
FROM FEATURELIST
WHERE FEATURELIST.Product_ID = P1.Product_ID)
MINUS
( SELECT FEATURELIST.feature_id
FROM FEATURELIST
WHERE FEATURELIST.Product_ID = P2.Product_ID )
)
GROUP BY P1.PNO;