Complete the code to create a CTE named recent_orders that selects orders from the last 30 days.
WITH recent_orders AS (SELECT * FROM orders WHERE order_date > CURRENT_DATE - INTERVAL '[1] days') SELECT * FROM recent_orders;
The CTE filters orders from the last 30 days using the interval '30 days'.
Complete the code to select customer_id and total order count using a subquery.
SELECT customer_id, (SELECT COUNT(*) FROM orders WHERE orders.customer_id = customers.customer_id) AS order_count FROM customers WHERE customer_id = [1];The customer_id is a number, so it should be used without quotes in the WHERE clause.
Fix the error in the CTE query that calculates average order amount per customer.
WITH avg_order AS (SELECT customer_id, AVG(order_amount) AS avg_amount FROM orders GROUP BY [1]) SELECT * FROM avg_order;The GROUP BY clause must use customer_id to calculate average order amount per customer.
Fill both blanks to write a query that compares performance by selecting orders using a CTE and a subquery.
EXPLAIN ANALYZE WITH recent_orders AS (SELECT * FROM orders WHERE order_date > CURRENT_DATE - INTERVAL '[1] days') SELECT * FROM customers WHERE customer_id IN (SELECT customer_id FROM recent_orders WHERE total > [2]);
The CTE filters recent orders within 30 days, and the subquery filters orders with total greater than 50.
Fill all three blanks to write a query that uses a CTE to calculate total sales per product, filters by minimum sales, and orders results.
WITH sales_summary AS (SELECT product_id, SUM(quantity * price) AS total_sales FROM sales GROUP BY [1]) SELECT product_id, total_sales FROM sales_summary WHERE total_sales > [2] ORDER BY [3] DESC;
The query groups by product_id, filters products with sales over 1000, and orders by total_sales descending.