Reading these queries is not the same as writing them. Open a SQL editor and write each one from scratch. If you get stuck, re-read the specific lesson — do not copy-paste solutions.
| Table | Columns |
|---|---|
| customers | customer_id (PK), first_name, last_name, email, city, created_at |
| orders | order_id (PK), customer_id (FK), order_date, total_amount, status, coupon_code |
| order_items | item_id (PK), order_id (FK), product_id (FK), quantity, unit_price |
| products | product_id (PK), product_name, category, price, stock_quantity |
| api_logs | log_id (PK), endpoint, response_time_ms, status_code, log_date |
Write a single query that shows a daily dashboard: order_date, daily_orders, daily_revenue, 7-day moving average revenue, running total revenue, and the day-over-day percentage change in revenue. Use multiple window functions in one query.
-- Hint: Combine SUM, AVG, and LAG as window functions
SELECT
order_date,
COUNT(*) AS daily_orders,
SUM(total_amount) AS daily_revenue,
ROUND(AVG(SUM(total_amount)) OVER(
ORDER BY order_date
ROWS BETWEEN 6 PRECEDING AND CURRENT ROW
), 2) AS seven_day_avg,
SUM(SUM(total_amount)) OVER(
ORDER BY order_date
) AS cumulative_revenue,
ROUND(
(SUM(total_amount) - LAG(SUM(total_amount)) OVER(ORDER BY order_date))
* 100.0 / NULLIF(LAG(SUM(total_amount)) OVER(ORDER BY order_date), 0),
2
) AS pct_change
FROM orders
GROUP BY order_date
ORDER BY order_date;If you solved the challenge exercise, you can write analytics queries that power real dashboards. This is a skill that separates a senior QA engineer from a junior one.
Key Point: Practice writing aggregate and window function queries by hand. The challenge exercise combines everything you learned in this chapter.