使用 CTE 篩選資料
使用 CTE 的一大重點,是先在 CTE 裡篩選資料,再把結果用在後續查詢。這樣能減少進入最終查詢的資料量,降低整體查詢成本。這個查詢要找出那些包含單價超過 $150 商品之訂單的訂單狀態。
本練習屬於課程
BigQuery 入門
練習說明
- 建立新的 CTE
orders,篩選單價超過 $150 的訂單,並對order_items做 UNNEST 以取得price欄位。 - 將 CTE 的結果與
ecomm_order_details資料集做 JOIN,計算各個order_status的筆數,並以在每個狀態中的訂單COUNT來彙總。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
-- Add the correct items to finish our filtered CTE
-- Create a new CTE with the name orders
WITH ___ AS (
SELECT order_id
-- Add the correct column for the order item details
FROM ecommerce.ecomm_orders, UNNEST(___) items
-- Fill in the correct column for the item price
WHERE items.___ > 150
)
SELECT
-- Aggregate to find the total number of orders
___(order_id),
-- Add the column for the status of the order
___
FROM ecommerce.ecomm_order_details od
JOIN orders o USING (order_id)
GROUP BY order_status