本文へスキップ
martechfarmDATA & TECHNOLOGY DOCS

すべての記事のタイトル・本文を検索

JOIN

1 件

タイトルを選ぶと本文が開きます

SQL練習問題:商品カテゴリ別の売上と粗利を集計する

本文
記事一覧へ ↑

SQL練習問題:商品カテゴリ別の売上と粗利を集計する

難易度: 中級 / 使用テーブル: 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後は行数が増えやすいため、注文単位、明細単位、ユーザー単位のどの粒度で集計しているかを必ず確認します。

SQL練習場でこの問題を試す