I have a table ProductDeliveryModes as:
ProductId DeliveryId
P101 D1
P101 D2
P101 D3
P102 D1
P102 D2
P102 D3
P103 D1
I need to get products which support all delivery modes (D1, D2, D3). From looking at the table the products should be: P101 and P102.
The query that I formed to get the solution is:
SELECT ProductId
FROM (SELECT DISTINCT ProductId,
DeliveryId
FROM ProductDeliveryModes) X
WHERE X.DeliveryId IN ( 'D1', 'D2', 'D3' )
GROUP BY ProductId
HAVING COUNT(*) = 3
The problem that I see in my solution is that one should know the count of the total number of delivery modes. We could make the count dynamic by getting the count from Sub-query.
Is there a better solution ?
I believe you can use
DISTINCT
withCOUNT
function to get the same result:Check the example.
You can simple store the distinct delivery count in a variable and used it. If you need to do this in a single query, this is one of the possible ways:
See the example.