Common table expressions

Introduktion till BigQuery

Matthew Forrest

Field CTO

Vad är en CTE?

-- The WITH keywords start the CTE
WITH our_cte AS (
  SELECT column1, column2
  FROM table
)


/* The CTE is contained in parentheses and can be used as a table in the main query below */ SELECT * FROM our_cte
Introduktion till BigQuery

Underfrågor vs. CTE:er

Underfråga

SELECT *
FROM (
  SELECT order_id, status
  FROM ecommerce.ecomm_order_status
) AS subquery

CTE

WITH cte_name AS (
  SELECT order_id, status
  FROM ecommerce.ecomm_order_status
)
SELECT *
FROM cte_name
Introduktion till BigQuery

Skriva CTE:er

-- All CTEs begin with the WITH keyword
WITH cte_name AS


-- The CTE is contained in parentheses (SELECT col_1, col_2 FROM tablename WHERE col_1 > 10 )
-- The new CTE 'cte_name' is only accessible within the scope of this query SELECT * FROM cte_name LIMIT 10
Introduktion till BigQuery

Använda flera CTE:er

WITH orders AS (
  SELECT order_id, status
  FROM ecommerce.ecomm_order_status
),

-- Additional CTEs do not reuse the WTIH keyword and are separated by commas order_details AS ( SELECT orders.*, details.order_items FROM ecommerce.ecomm_orders details ```
Introduktion till BigQuery

Filtrera data med CTE:er

WITH filtered_data AS (
  SELECT *
  FROM ecommerce.ecomm_orders
  -- Here, we filter the data in our CTE
  WHERE order_status = 'delivered'
)
SELECT order_id, order_status
FROM filtered_data
| order_id | order_status |
|----------|--------------|
| 1        | delivered    |
| 2        | delivered    |
Introduktion till BigQuery

Optimera frågor med CTE:er

WITH precomputed_data AS (
  SELECT order_id, SUM(payment_value) AS total
  FROM ecommerce.ecomm_payments
  GROUP BY order_id
)
SELECT *
FROM precomputed_data
WHERE total > 1000
| order_id | total   |
|----------|---------|
| 1        | 50000   |
| 2        | 8000    |
Introduktion till BigQuery

Slå ihop data med CTE:er

WITH cte1 AS (
  SELECT order_id, status
  FROM ecommerce.ecomm_order_status
),
cte2 AS (
  SELECT order_id, order_items
  FROM ecommerce.ecomm_orders
)
SELECT *
FROM cte1
JOIN cte2 USING (order_id)
Introduktion till BigQuery

Nu kör vi en övning!

Introduktion till BigQuery

Preparing Video For Download...