-
Notifications
You must be signed in to change notification settings - Fork 0
/
Top 5 Customers Subquery
27 lines (27 loc) · 1.14 KB
/
Top 5 Customers Subquery
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
# This subquery shows how many of the top 5 customers are based within each country.
SELECT D.country,
COUNT(DISTINCT A.customer_id) as all_customer_count,
COUNT(DISTINCT Top_5_customers) as Top_customer_count
FROM Customer A
INNER Join address B ON A.address_id=B.address_id
INNER JOIN city C ON B.city_id=C.city_id
INNER JOIN Country D ON C.country_id=D.country_id
LEFT JOIN
(SELECT A.customer_id,A.first_name AS customer_first_name,
A.last_name AS Customer_last_name,
D.country,C.city,SUM(E.amount) as total_amount_paid
From Customer A
INNER JOIN address B ON A.address_id = B.address_id
INNER JOIN city C ON B.city_id = C.city_id
INNER JOIN country D ON C.country_ID = D. country_ID
INNER JOIN payment E ON A.customer_id=E.customer_id
WHERE city IN ('Aurora','Atlixco','Xintai','Adoni',
'Dhule(Dhulia)','Kurashiki','Pingxiang',
'Sivas','Celaya','So Leopoldo')
GROUP BY city, country,customer_first_name,
customer_last_name,A.customer_id
ORDER by total_amount_paid DESC
LIMIT 5) as Top_5_Customers ON A.customer_id=top_5_customers.customer_id
GROUP BY D.Country
HAVING COUNT (top_5_customers)>0
ORDER BY (Top_customer_count),(all_customer_count) DESC