I'm trying to check whether certain features in Product A are all also featured in Product B. We count the amount of how many such Product B's there are that fully fulfill all of the features of Product A.
My query returns the correct value for the Count, however, I want it to display 0 where there are no such Product B's that have the features of Product A. At the moment, it is only returning the values where the count is greater than 1.
For a further explanation please refer to the following code:
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;
This returns something that looks like:
Product_ID | NUMBER
1 2
5 7
13 2
17 4
I want it to return the full Product_ID list.. so something like this:
Product_ID | NUMBER
1 2
2 0
3 0
4开发者_开发问答 0
5 7
6 0
7 0
.. ..
17 4
Using oracle sql.
A simple solution might be to UNION
all products with a default COUNT
of 0 and perform an additional GROUP BY
on the results.
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
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;
精彩评论