You are on page 1of 4

CIS310 S03 Type 10-13

1. Which customers(cust_id) have sales reps 129 or 299 but not both? (Type 11) SELECT cust_id FROM sales_order WHERE (sales_rep = 129 or sales_rep = 299) AND NOT cust_id IN (SELECT o1.cust_id FROM sales_order o1, sales_order o2 WHERE o1.cust_id = o2.cust_id AND o1.sales_rep = 129 AND o2.sales_rep = 299) cust_id 131 143 167 180 168 168 201 198 2. Which customers(cust_id) have sales reps 129 or 299 but not both? (Type 11)USE A CORRELATED SUBQUERY ! SELECT cust_id FROM sales_order s WHERE (sales_rep = 129 or sales_rep = 299) AND NOT Exists (SELECT o1.cust_id FROM sales_order o1, sales_order o2 WHERE o1.cust_id = s.cust_id AND o2.cust_id = s.cust_id AND o1.sales_rep = 129 AND o2.sales_rep = 299)

Nice! cust_id 131 143 167 180 168 168 201 198 3. Which customers(cust_id) have purchased from sales reps 129, 195, or 299 but not all three? SELECT DISTINCT cust_id FROM sales_order WHERE sales_rep IN (129, 195, 299) AND NOT cust_id IN ( SELECT o1.cust_id FROM sales_order o1, sales_order o2, sales_order o3 WHERE o1.cust_id = o2.cust_id AND o1.cust_id = o3.cust_id AND o1.sales_rep = 129 AND o2.sales_rep = 195 AND o3.sales_rep = 299 ) ORDER BY cust_id Results: (Note: 101 and 117 were eliminated because they purchased from all three) 103 104 105 107 109 110 111

112 113 114 115 116 119 4. Which products(prod_id) have the oldest shipping date? (Type 12) SELECT distinct(prod_id) from sales_order_items where not ship_date in (select s1.ship_date from sales_order_items s1, sales_order_items s2 where s1.ship_date > s2.ship_date) order by prod_id prod_id 300 301 302 This works but MIN is easier. 5. Which contact is the only contact named Amy? (Type 10) SELECT first_name, last_name from contact group by first_name,last_name having count(*)=1 and max(first_name)='Amy' Amy Schott Im not sure the question makes sense. What should the query return if there is more than one contact named Amy? Since you are grouping on both first name and last name, your query is really asking to see all the contacts named Amy whose first

and last name is unique. See what happens if you substitute Paul for Amy. A more interesting question would be: 6. Which first names appear at least twice in the contact table? SELECT first_name, count(*) from contact group by first_name having count(*) > 1 but thats not a type 10.

You might also like