難易度: 中級 / 使用テーブル: order_items, products
問題
order_itemsとproductsをJOINし、商品カテゴリ別に売上と推定粗利を集計してください。
スターターSQL
SELECT
p.category,
SUM(oi.quantity * oi.unit_price) AS sales_amount
FROM order_items oi
JOIN products p ON oi.product_id = p.id
GROUP BY p.category
ORDER BY sales_amount DESC;解答例
SELECT
p.category,
COUNT(DISTINCT oi.order_id) AS order_count,
SUM(oi.quantity * oi.unit_price) AS sales_amount,
ROUND(SUM(oi.quantity * oi.unit_price * p.gross_margin_rate), 0) AS gross_profit
FROM order_items oi
JOIN products p ON oi.product_id = p.id
GROUP BY p.category
ORDER BY gross_profit DESC;見るべきポイント
JOIN後は行数が増えやすいため、注文単位、明細単位、ユーザー単位のどの粒度で集計しているかを必ず確認します。