Skip to content

Commit

Permalink
Nested CTE insert
Browse files Browse the repository at this point in the history
  • Loading branch information
Ben Brumm committed Aug 1, 2024
1 parent 84d4345 commit 9832aa3
Showing 1 changed file with 43 additions and 21 deletions.
64 changes: 43 additions & 21 deletions courses/course_postgres_mastery/26_nested_cte.sql
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,16 @@
Nested CTE
*/

--most valuable customers and their active addresses?


--SQL 01
--Most Valuable Customers
SELECT
c.customer_id,
c.first_name,
c.last_name,
c.email,
cn.country_name,
cs.total_order_amount,
cs.avg_order_amount
FROM customer c
INNER JOIN customer_address ca ON c.customer_id = ca.customer_id
INNER JOIN address a ON ca.address_id = a.address_id
INNER JOIN address_status s ON ca.status_id = s.status_id
INNER JOIN country cn ON a.country_id = cn.country_id
INNER JOIN (
--customer ID and their stats
SELECT
Expand All @@ -36,11 +30,18 @@ INNER JOIN (
) o
GROUP BY o.customer_id
) cs ON c.customer_id = cs.customer_id
WHERE s.address_status = 'Active'
ORDER BY cs.total_order_amount DESC;


--without addresses
--SQL 02
WITH order_value AS (
SELECT
co.customer_id,
co.order_id,
SUM(ol.price) AS order_amount
FROM cust_order co
INNER JOIN order_line ol ON co.order_id = ol.order_id
GROUP BY co.customer_id, co.order_id
)
SELECT
c.customer_id,
c.first_name,
Expand All @@ -55,16 +56,37 @@ INNER JOIN (
o.customer_id,
SUM(o.order_amount) AS total_order_amount,
ROUND(AVG(o.order_amount), 2) AS avg_order_amount
FROM (
--order amounts
SELECT
co.customer_id,
co.order_id,
SUM(ol.price) AS order_amount
FROM cust_order co
INNER JOIN order_line ol ON co.order_id = ol.order_id
GROUP BY co.customer_id, co.order_id
) o
FROM order_value o
GROUP BY o.customer_id
) cs ON c.customer_id = cs.customer_id
ORDER BY cs.total_order_amount DESC;


--SQL 03
WITH order_value AS (
SELECT
co.customer_id,
co.order_id,
SUM(ol.price) AS order_amount
FROM cust_order co
INNER JOIN order_line ol ON co.order_id = ol.order_id
GROUP BY co.customer_id, co.order_id
),
customer_order_stats AS (
SELECT
o.customer_id,
SUM(o.order_amount) AS total_order_amount,
ROUND(AVG(o.order_amount), 2) AS avg_order_amount
FROM order_value o
GROUP BY o.customer_id
)
SELECT
c.customer_id,
c.first_name,
c.last_name,
c.email,
cs.total_order_amount,
cs.avg_order_amount
FROM customer c
INNER JOIN customer_order_stats cs ON c.customer_id = cs.customer_id
ORDER BY cs.total_order_amount DESC;

0 comments on commit 9832aa3

Please sign in to comment.