Data Lake • Write your own SQL

Combine two tables

How did each region do against its budget?

Try this

  • Run this on my data lake: WITH sales AS ( SELECT region, date_trunc('month', order_date) AS month, SUM(amount) AS revenue FROM samples.shop_orders GROUP BY 1, 2 ) SELECT s.region, s.revenue, b.amount AS budget, s.revenue - b.amount AS gap FROM sales s JOIN samples.shop_budget b ON b.region = s.region AND CAST(b.month AS DATE) = CAST(s.month AS DATE) WHERE s.month = DATE '2026-10-01' ORDER BY gap

In plain words

What is it?

One table holds sales and another holds plans. This puts them side by side.

How does it work?

WITH names a first step: sales by region and month. JOIN then matches each of those lines with the budget line for the same region and month.

Good to know

If a match is repeated on either side, totals get doubled. Check the number of rows you get back. Load shop_budget too for this one.

Then try

Keep every customer, matched or not

  • Run this on my data lake: SELECT a.customer_id, a.orders, b.first_order FROM (SELECT customer_id, COUNT(*) AS orders FROM samples.shop_orders GROUP BY customer_id) a LEFT JOIN (SELECT customer_id, MIN(order_date) AS first_order FROM samples.shop_orders GROUP BY customer_id) b ON b.customer_id = a.customer_id ORDER BY a.orders DESC LIMIT 5