I'm new to sub-queries and think I need them in the following situation, but am not sure how to proceed.
I have the following query. Now, I have two things I need to add to the query =
- For CA consumers, they can only have 1 car accident (car_acc), while in other states it does not matter.
In FL, MD, NH, and WA currently insured can be 0 (boolean), while in the other states it should only be 1.
SELECT Count(*), Avg(sl.our_cost), Avg(sl.purchase_price) FROM sold_leads AS sl INNER JOIN leads AS l ON l.id = sl.lead_id INNER JOIN contacts AS c ON c.lead_id = l.id INNER JOIN drivers AS d ON d.lead_id = l.id WHERE c.state IN( 'AK', 'AL', 'AR', 'AZ', 'CA', 'CO', 'CT', 'DC', 'DE', 'FL', 'GA', 'HI', 'IA', 'ID', 'IL', 'IN', 'KS', 'KY', 'LA', 'MD', 'ME', 'MI', 'MN', 'MO', 'MS', 'MT', 'NC', 'ND', 'NE', 'NH', 'NJ', 'NM', 'NV', 'NY', 'OH', 'OK', 'OR', 'PA', 'RI', 'SC', 'SD', 'TN', 'TX', 'UT', 'VA', 'VT', 'WA', 'WI', 'WV', 'WY' ) AND l.leg = 0 AND ( Datediff(CURRENT_DATE, d.date_of_birth) / 365 ) >= 50 AND l.create_date >= '2012-1-1';
How would I go about adding these subqueries to my query? Is there a better method to find that information?
EDIT:
I should mention that it should have read 1 'car accident' or 'violation'. I have two different tables with car accidents and violations, and so for CA residents, I need only those who have 1 accident OR 1 violation.