As we gain enough knowledge related to writing queries, let us explore some advanced DML Operations.
We can insert query results into a table using INSERT
with SELECT
.
As long as columns specified for table in INSERT
statement and columns projected in SELECT
clause match, it works.
We can also use query results for UPDATE
as well as DELETE
.
%%sql
SELECT o.order_customer_id,
to_char(o.order_date, 'yyyy-MM') AS order_month,
count(1) AS order_count,
round(sum(order_item_subtotal)::numeric, 2) AS order_revenue
FROM orders o
JOIN order_items oi
ON o.order_id = oi.order_item_order_id
GROUP BY o.order_customer_id,
to_char(o.order_date, 'yyyy-MM')
ORDER BY order_month,
order_count DESC
LIMIT 10
order_customer_id | order_month | order_count | order_revenue |
---|---|---|---|
4257 | 2013-07 | 10 | 2059.75 |
5293 | 2013-07 | 10 | 2781.73 |
9103 | 2013-07 | 9 | 1587.85 |
7473 | 2013-07 | 9 | 1244.90 |
2071 | 2013-07 | 9 | 1629.84 |
32 | 2013-07 | 9 | 2009.75 |
488 | 2013-07 | 9 | 1365.82 |
7073 | 2013-07 | 9 | 1377.83 |
8709 | 2013-07 | 8 | 1349.87 |
1498 | 2013-07 | 8 | 1619.88 |
customer_id | order_month | order_count | order_revenue |
---|---|---|---|
12 | 2013-07 | 2 | None |
16 | 2013-07 | 1 | None |
17 | 2013-07 | 2 | None |
19 | 2013-07 | 3 | None |
32 | 2013-07 | 9 | None |
45 | 2013-07 | 4 | None |
48 | 2013-07 | 4 | None |
54 | 2013-07 | 2 | None |
58 | 2013-07 | 4 | None |
64 | 2013-07 | 2 | None |
%%sql
UPDATE customer_order_metrics_mthly comd
SET
(order_count, order_revenue) = (
SELECT count(1),
round(sum(order_item_subtotal)::numeric, 2)
FROM orders o
JOIN order_items oi
ON o.order_id = oi.order_item_order_id
WHERE o.order_customer_id = comd.customer_id
AND to_char(o.order_date, 'yyyy-MM') = comd.order_month
AND to_char(o.order_date, 'yyyy-MM') = '2013-08'
AND comd.order_month = '2013-08'
GROUP BY o.order_customer_id,
to_char(o.order_date, 'yyyy-MM')
)
WHERE EXISTS (
SELECT 1 FROM orders o
WHERE o.order_customer_id = comd.customer_id
AND to_char(o.order_date, 'yyyy-MM') = comd.order_month
AND to_char(o.order_date, 'yyyy-MM') = '2013-08'
) AND comd.order_month = '2013-08'
customer_id | order_month | order_count | order_revenue |
---|---|---|---|
2 | 2013-08 | 5 | 769.82 |
13 | 2013-08 | 5 | 1065.93 |
14 | 2013-08 | 3 | 459.97 |
18 | 2013-08 | 1 | 129.99 |
20 | 2013-08 | 2 | 739.91 |
22 | 2013-08 | 5 | 769.96 |
24 | 2013-08 | 2 | 399.91 |
25 | 2013-08 | 1 | 129.99 |
33 | 2013-08 | 3 | 929.92 |
34 | 2013-08 | 4 | 789.92 |