始める無料で始める

CTEで最適化する

CTE を使うと、集約などの計算をメインのクエリでデータを扱う前に処理できるため、クエリを最適化できます。

たとえば、注文内のアイテム数ごとに支払い回数の最大値を調べたいとします。この演習では、CTE を使ってそれを効率的に行う方法を学びます。

この演習はコースの一部です

BigQuery入門

コースを見る

演習の手順

  • サブクエリとメインクエリの両方に正しい集約関数を追加してください。
  • メインクエリで order_items 列を2回使用し、ARRAY_LENGTH を使って各注文のアイテム数を求めてください。

実践的なインタラクティブ演習

このサンプルコードを完成させて、この演習に挑戦してみましょう。

WITH payments AS (
  SELECT
    -- Use the correct aggregate to find the highest number of payments
    ___(payment_sequential) AS num_payments,
    order_id
  FROM ecommerce.ecomm_payments 
  -- Group the results by order
  GROUP BY ___)
     
SELECT
  -- Add the correct function to find the length or number of order items
  ___(o.order_items) AS num_items,
  MAX(p.num_payments) AS max_payments
FROM ecommerce.ecomm_orders o
JOIN payments p
-- Add the correct keyword to join using the same column
___ (order_id)
-- Add the correct function to find the length or number of order items
GROUP BY ___(o.order_items)
コードを編集して実行