Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

table stores has two columns like store_id and products. Write a SQL query to find store_ids which sell only shampoo and biscuit

Store should sell only two products and that too only shampoo and biscuit

For example
enter image description here

Output:
enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

my query: –

SELECT *
FROM (SELECT store_id AS gp_str
      FROM (SELECT store_id,
                   COUNT(product) AS prd_cnt
            FROM stores
            GROUP BY store_id) x
      WHERE x.prd_cnt = 2) y
     LEFT JOIN stores ON y.gp_str = stores.store_id;

My query gave me result of stores which sell only two products but I wanted stores which sell two products which are shampoo and biscuit only.

>Solution :

SELECT store_id
FROM stores
GROUP BY store_id
HAVING COUNT(DISTINCT product) = 2
    AND COUNT(*) = SUM(CASE WHEN product IN ('shampoo','biscuit') THEN 1 ELSE 0 END);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading