-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsql_union_ex9.sql
More file actions
42 lines (33 loc) · 780 Bytes
/
Copy pathsql_union_ex9.sql
File metadata and controls
42 lines (33 loc) · 780 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
-- From the following table, write a SQL query to find those salespersons and customers who have placed more than one order. Return ID, name.
-- Attempt one
SELECT customer_id AS ID, cust_name AS name
FROM customer
WHERE customer_id = ANY
(SELECT customer_id
FROM orders
GROUP BY customer_id
HAVING COUNT(*) > 1)
UNION
SELECT salesman_id, name
FROM salesman
WHERE salesman_id = ANY
(SELECT salesman_id
FROM orders
GROUP BY salesman_id
HAVING COUNT(*) > 1)
ORDER BY 2 ASC;
-- Second attempt
SELECT customer_id AS ID, cust_name AS name
FROM customer a
WHERE 1 <
(SELECT COUNT(*)
FROM orders b
WHERE a.customer_id = b.customer_id)
UNION
SELECT salesman_id AS ID, name
FROM salesman a
WHERE 1 <
(SELECT COUNT(*)
FROM orders b
WHERE a.salesman_id = b.salesman_id)
ORDER BY 2;