-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCommon Table Expression
More file actions
19 lines (19 loc) · 1.16 KB
/
Common Table Expression
File metadata and controls
19 lines (19 loc) · 1.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
WITH top_5_customers_cte(customer_id,first_name,last_name,country,city,total_amount_paid) AS
(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)
SELECT D.country,COUNT(DISTINCT A.customer_id)as all_customer_count,
COUNT(DISTINCT top_5_customers_cte.customer_id) 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 top_5_customers_cte ON A.customer_id=top_5_customers_cte.customer_id GROUP BY D.Country
HAVING COUNT (top_5_customers_cte)>0
ORDER BY (Top_customer_count),(all_customer_count) DESC