I need to find all other related records for an ID if a certain value exists.
I have almost no SQL experience and work primarily on a front end design UI, rather than writing the code myself.
The basic query is:
For a given period, if any customer placed an order in that period, I’d like to see all orders for those customers.
So looking for all orders for any customer who placed an order in April:
Customer Order Month John Apples January John Pears January John Oranges February John Bananas April Amy Apples March Amy Pears May Amy Oranges July Amy Bananas September Larry Apples January Larry Pears April Larry Oranges August Larry Bananas November Marge Apples April Marge Pears May Marge Oranges June Marge Bananas July
Expected result would be:
Customer Order Month John Apples January John Pears January John Oranges February John Bananas April Larry Apples January Larry Pears April Larry Oranges August Larry Bananas November Marge Apples April Marge Pears May Marge Oranges June Marge Bananas July
Any help provided would be greatly appreciated.
Advertisement
Answer
I would write it literally like your described it: Find all the customers from April and then show all the orders for those customers.
SELECT * FROM OrderTable ot WHERE ot.Customer IN (SELECT DISTINCT Customer FROM OrderTable WHERE Month = 'April')