Saturday, 23 April 2016

SQL Query : Fetching records which exists in other table

Problem : Select only the customer IDs (Not duplicates and sorted in ascending) who purchased at least one product in "Books" or "Garden" category.

  
 
Output CUSTOMER_ID column - matching condition, sorted and without duplicates
  

SQL   
SELECT DISTINCT c.customer_id FROM customer c, purchase_order po, order_product op, product p, product_category pc
WHERE c.customer_id=po.customer_id AND po.order_id=op.order_id AND op.product_id=p.product_id AND p.product_category_id=pc.product_category_id AND pc.name IN ('Books', 'Garden')
ORDER BY c.customer_id

No comments:

Post a Comment

Note: only a member of this blog may post a comment.