1. 簡介
在本程式碼實驗室中,您將使用 BigQuery Graph、BigQuery Measures 和對話式數據分析,分析線上零售商的漏斗頂端、漏斗底部和統合行銷指標。
在零售和電子商務領域,顧客的購物路徑很少是線性的。消費者在結帳前,會先接觸付費搜尋、付費社群活動、影片、自然搜尋和電子郵件廣告活動。行銷主管經常會遇到相同的問題:
- 哪些廣告活動確實帶來高利潤收益,哪些只是在燒廣告費?
- 不同的歸因模式 (最初接觸、最終接觸、線性) 如何影響管道排名?
- 如何製作廣告活動預算報表,並在網站接觸點和訂單委刊項旁顯示,同時避免重複計算?

建構項目
- 名為
thelook_graph.eCommerce_Integrated的屬性圖,用於連結廣告活動、接觸點、使用者、訂單、訂單項目和產品,並直接在節點上宣告 10 項測量指標。 - 高階主管廣告投資報酬率評量表:在單一查詢中,結合精細安全的預算和支出匯總,以及 4 躍點利潤歸因。
- (選用) 以圖表為基準的對話式數據分析資料代理,業務使用者可以透過自然語言查詢。

課程內容
每個步驟都是一個里程碑,您必須先驗證,才能繼續進行:
- 在 BigQuery 資料表和檢視表上建立屬性圖譜模型,並在節點上宣告測量指標。
- 透過
INFORMATION_SCHEMA.PROPERTY_GRAPHS檢查測量指標。 - 使用一般 SQL join 重現笛卡兒扇出,然後使用
GRAPH_EXPAND和AGG()匯總漏斗頂端和底部的指標,不重複計算。 - 使用
GRAPH_TABLE比較最初接觸、最終接觸和線性歸因。 - 計算 4 躍點毛利和毛利率:從接觸點到產品成本。
- 使用純 ISO GQL 追蹤顧客的轉換歷程。
- 將兩種查詢樣式合併為單一主管廣告投資報酬率評量表。
- (選用) 依據圖表建立對話式數據分析代理,並發布至 Gemini Enterprise。
核心問題:資料精細度和笛卡兒扇出
在本程式碼實驗室中,「精細程度」是指一列代表的內容。廣告活動預算位於廣告活動層級 (每個廣告活動 1 列)。網路點擊位於接觸點層級 (數百萬列)。訂單明細項目位於訂單項目層級。
在關聯式資料倉儲中,回答歸因問題代表要彙整精細程度截然不同的資料表 (campaigns ➔ touchpoints ➔ orders ➔ order_items ➔ products)。這會導致兩個問題:
- 笛卡兒扇出 (重複計算):將粗略資料列 (一個廣告活動預算) 與精細資料列 (每次點擊和每個委刊項) 彙整,會導致每個彙整資料列重複計算預算。簡單的
SUM()會將其加總數百萬次:在這個資料集中,單一 $60,000 美元的電子郵件預算,加入訂單委刊項後,會落在超過一百萬個資料列上。 - 複雜且不穩定的 SQL:多躍路徑分析需要巢狀 CTE、視窗函式或
ANY_VALUE()解決方法,但只要有人變更GROUP BY,這些方法就會失效。
BigQuery Graph 和測量指標如何解決問題
有了 BigQuery Graph,您只需將所有關係宣告為屬性圖譜一次,即可在現有 BigQuery 資料表和檢視表上建立邏輯層。資料不會複製到獨立的圖形資料庫。接著,您會以兩種互補的方式查詢同一個圖表:
GRAPH_EXPAND+AGG()(標準 SQL):傳遞start_node => "touchpoints"取得漏斗頂端指標,或傳遞start_node => "order_items"取得漏斗底部指標,並在宣告的精細程度匯總各項測量結果。語法是純SELECT ... GROUP BY,因此適用於 Looker、Tableau 或任何商業智慧工具。GRAPH_TABLE和 ISO GQL (圖表模式比對):遍歷多個躍點來比較歸因模式、將接觸點連結至產品銷貨成本 (COGS) 以取得實際毛利率,以及對應個別顧客歷程。
BigQuery 測量指標 (MEASURE(...)) 會將各項業務指標 (total_campaign_budget、total_ad_spend、total_clicks、unique_reach、total_users、total_orders、gross_revenue、total_items_sold、avg_cost、avg_retail_price) 嵌入擁有該指標的節點,因此在數學上不可能重複計算。最後,對話式數據分析資料代理會以圖譜為基準,讓業務使用者能以自然語言提出這些問題。
軟硬體需求
- 網路瀏覽器,例如 Chrome。
- 已啟用計費功能的 Google Cloud 專案。
- 該專案的 IAM 角色:BigQuery 管理員 (
roles/bigquery.admin)、BigQuery 資源管理員 (roles/bigquery.resourceAdmin) (用於建立預留項目),以及 Service Usage 管理員 (roles/serviceusage.serviceUsageAdmin) (用於啟用 API)。專案擁有者則涵蓋這三種權限。 - Cloud Shell (用於
gcloud和bq指令) 和 BigQuery Studio (用於 SQL)。 - 具備 SQL (
JOIN、GROUP BY、CTE) 的實務知識。不需具備圖表查詢經驗。 - (選用,僅限最後一個步驟) Gemini Enterprise 應用程式的存取權。
本程式碼實驗室適合中級資料分析師、數據分析工程師和開發人員。
預估時間:約 90 分鐘 (如果略過選用的 Gemini Enterprise 步驟,則約 80 分鐘)
預估費用:不到 $5 美元。載入資料不需付費;查詢會在無伺服器 BigQuery Enterprise 預留項目上執行,基準運算單元為 0,最後您會刪除該預留項目。
2. 事前準備
建立 Google Cloud 專案
- 在 Google Cloud 控制台的專案選取器頁面,選取或建立 Google Cloud 專案。
- 請確認您已為專案啟用計費功能。
啟動 Cloud Shell
您會在 Google Cloud Shell 中執行指令,其中已預先安裝 Google Cloud CLI (gcloud) 和 BigQuery CLI (bq)。
- 在 Google Cloud 控制台,點選頂端導覽列中的「啟用 Cloud Shell」。
- 如果系統提示,請確認授權。
設定環境變數
在 Cloud Shell 中,設定程式碼實驗室其餘部分會用到的變數:
export PROJECT_ID=$(gcloud config get-value project)
export REGION="US"
export RESERVATION_NAME="graph-enterprise-reservation"
echo "Using project ${PROJECT_ID} in location ${REGION}"
啟用 API
啟用 BigQuery 和 BigQuery Reservation API。(選用的對話式數據分析步驟會在稍後啟用專屬 API)。
gcloud services enable \
bigquery.googleapis.com \
bigqueryreservation.googleapis.com \
--project=${PROJECT_ID}
建立 BigQuery Enterprise 預留項目和指派作業
根據 BigQuery Graph 說明文件,GQL 查詢 (GRAPH_TABLE 和 GRAPH ... MATCH) 必須使用 Enterprise 或 Enterprise Plus 版本的預留項目,而 GRAPH_EXPAND 查詢也可以採用隨選計價模式。建立自動調度資源預留項目,並將基準運算單元設為 0,這樣閒置時就不會產生費用:
# 1. Create an Enterprise reservation (0 baseline slots, autoscale up to 100)
bq mk --reservation \
--project_id=${PROJECT_ID} \
--location=${REGION} \
--edition=ENTERPRISE \
--slots=0 \
--autoscale_max_slots=100 \
--ignore_idle_slots=true \
${RESERVATION_NAME}
# 2. Assign your project's queries to the reservation
bq mk --reservation_assignment \
--project_id=${PROJECT_ID} \
--location=${REGION} \
--reservation_id=${RESERVATION_NAME} \
--job_type=QUERY \
--assignee_type=PROJECT \
--assignee_id=${PROJECT_ID}
驗證預留項目
執行任何圖表查詢前,請先確認指派作業是否存在。如果缺少這個項目,稍後在程式碼實驗室中執行 GQL 查詢時,就會發生版本錯誤。
bq ls --reservation_assignment \
--project_id=${PROJECT_ID} \
--location=${REGION}
預期輸出內容 (您的作業 ID 會是不同的數字):
name jobType assignee
------------------------------------------------------------------ --------- --------------------------
PROJECT_ID:US.graph-enterprise-reservation.7664235470433641991 QUERY projects/PROJECT_ID
3. 建立資料集並載入範例資料
在這個步驟中,您會建立 thelook_graph 資料集,並從公開 bucket gs://sample-data-and-media/thelook_dataset_snapshot/ 載入 thelook_ecommerce 快照的五個基礎資料表。
資料表 | 資料列 | 一列代表的內容 (精細程度) |
| 100,000 | 已註冊的購物者,包含客層和獲客 |
| 125,270 | 結帳交易,包含 |
| 181,271 | 一個購買的委刊項,包含 |
| 29,120 | 目錄產品,包含 |
| 2,423,365 | 一次網站互動 ( |
方法 A:在 BigQuery Studio 中使用 SQL 載入 (建議)
開啟 BigQuery Studio,將下列內容貼到查詢編輯器,然後點選「執行」:
-- 1. Create the dataset
CREATE SCHEMA IF NOT EXISTS `thelook_graph`
OPTIONS (
location = 'US',
description = 'Marketing attribution and ROAS graph over the thelook_ecommerce snapshot'
);
-- 2. Users (100,000 rows)
LOAD DATA OVERWRITE `thelook_graph.users`
FROM FILES (
format = 'AVRO',
uris = ['gs://sample-data-and-media/thelook_dataset_snapshot/users/*.avro.gz'],
enable_logical_types = true
);
-- 3. Orders (125,270 rows)
LOAD DATA OVERWRITE `thelook_graph.orders`
FROM FILES (
format = 'AVRO',
uris = ['gs://sample-data-and-media/thelook_dataset_snapshot/orders/*.avro.gz'],
enable_logical_types = true
);
-- 4. Order items (181,271 rows)
LOAD DATA OVERWRITE `thelook_graph.order_items`
FROM FILES (
format = 'AVRO',
uris = ['gs://sample-data-and-media/thelook_dataset_snapshot/order_items/*.avro.gz'],
enable_logical_types = true
);
-- 5. Products (29,120 rows)
LOAD DATA OVERWRITE `thelook_graph.products`
FROM FILES (
format = 'AVRO',
uris = ['gs://sample-data-and-media/thelook_dataset_snapshot/products/*.avro.gz'],
enable_logical_types = true
);
-- 6. Web events (2,423,365 rows)
LOAD DATA OVERWRITE `thelook_graph.events`
FROM FILES (
format = 'AVRO',
uris = ['gs://sample-data-and-media/thelook_dataset_snapshot/events/*.avro.gz'],
enable_logical_types = true
);
方法 B:在 Cloud Shell 中使用 bq 載入
或者,您也可以在 Cloud Shell 中執行下列指令:
bq --location=${REGION} mk --dataset \
--description "Marketing attribution and ROAS graph" \
${PROJECT_ID}:thelook_graph
for table in users orders order_items products events; do
bq load --replace --source_format=AVRO --use_avro_logical_types \
${PROJECT_ID}:thelook_graph.${table} \
"gs://sample-data-and-media/thelook_dataset_snapshot/${table}/*.avro.gz"
done
驗證負載
在 BigQuery Studio 執行這項查詢,並比較資料列數量:
SELECT table_id, row_count
FROM `thelook_graph.__TABLES__`
ORDER BY table_id;
預期輸出內容:
table_id | row_count |
| 2,423,365 |
| 181,271 |
| 125,270 |
| 29,120 |
| 100,000 |
如果 events 顯示的資料列較少,表示載入工作仍在執行中,請稍候片刻再重新執行查詢。
4. 建立行銷檢視表和歸因邊緣
thelook_ecommerce 資料集包含購物者、訂單和網站事件,但沒有行銷廣告活動資料。在這個步驟中,您會將三個物件新增至 thelook_graph,將其轉換為行銷歸因資料集:

marketing_campaigns(檢視畫面):第 4 季有 8 個廣告活動,涵蓋 5 個管道,並列出預算和目標廣告投資報酬率。touchpoints(檢視表):2,423,365 個網站事件,每個事件都標有廣告活動、管道和基準單次點擊出價 (CPC)。edge_influenced(表格):哪些接觸點影響了哪些訂單,以及最初接觸、最終接觸和線性歸因權重。
2a. 廣告活動參考資料檢視畫面
廣告活動預算是上游粗略資料:每個廣告活動一列。以下檢視畫面定義了 8 個廣告活動,並設定實際的第 4 季預算。
CREATE OR REPLACE VIEW `thelook_graph.marketing_campaigns` AS
SELECT 'Paid Search' AS channel, 'Q4_Search_Generic_Audio' AS campaign_name, 1500000.0 AS total_budget, 4.0 AS target_roas UNION ALL
SELECT 'Paid Search', 'Q4_Search_Brand_Electronics', 1100000.0, 5.0 UNION ALL
SELECT 'Paid Social', 'Q4_Meta_IG_Retargeting', 250000.0, 4.5 UNION ALL
SELECT 'Video', 'Q4_YouTube_Video_Awareness', 220000.0, 2.5 UNION ALL
SELECT 'Paid Social', 'Q4_TikTok_Prospecting_GenZ', 150000.0, 3.0 UNION ALL
SELECT 'Email Marketing', 'Q4_Email_Cart_Abandonment', 75000.0, 10.0 UNION ALL
SELECT 'Email Marketing', 'Q4_Email_VIP_Weekly_Drop', 60000.0, 8.0 UNION ALL
SELECT 'Organic', 'Organic_Search_SEO', 25000.0, 15.0;
2b. 接觸點檢視畫面
每個網站事件都已記錄 traffic_source (Adwords、Facebook、YouTube、Email 或 Organic)。檢視表會將每個來源對應至行銷管道,使用 MOD(e.id, 2) 將每個付費來源拆分為兩個廣告活動 (偶數事件 ID 歸入一個廣告活動,奇數 ID 歸入另一個廣告活動),並指派業界基準單次點擊出價:
| 頻道 | 廣告活動 (偶數/奇數事件 ID) | 單次點擊出價 |
| 付費搜尋 |
| $3.78 / $2.64 |
| 付費社群活動 |
| $1.85 / $0.99 |
| 影片 |
| $0.85 |
| 電子郵件行銷 |
| $0.12 美元 / $0.10 美元 |
| 自然 |
| $0.00 美元 |
這是檢視表,因此不會複製資料;240 萬個事件會在查詢時加上標記。
CREATE OR REPLACE VIEW `thelook_graph.touchpoints` AS
SELECT
e.id AS touchpoint_id,
e.user_id,
e.session_id,
e.created_at,
e.event_type,
e.browser,
e.traffic_source,
CASE
WHEN e.traffic_source = 'Adwords' AND MOD(e.id, 2) = 0 THEN 'Q4_Search_Generic_Audio'
WHEN e.traffic_source = 'Adwords' THEN 'Q4_Search_Brand_Electronics'
WHEN e.traffic_source = 'Facebook' AND MOD(e.id, 2) = 0 THEN 'Q4_Meta_IG_Retargeting'
WHEN e.traffic_source = 'Facebook' THEN 'Q4_TikTok_Prospecting_GenZ'
WHEN e.traffic_source = 'YouTube' THEN 'Q4_YouTube_Video_Awareness'
WHEN e.traffic_source = 'Email' AND MOD(e.id, 2) = 0 THEN 'Q4_Email_Cart_Abandonment'
WHEN e.traffic_source = 'Email' THEN 'Q4_Email_VIP_Weekly_Drop'
ELSE 'Organic_Search_SEO'
END AS campaign_name,
CASE
WHEN e.traffic_source = 'Adwords' THEN 'Paid Search'
WHEN e.traffic_source = 'Facebook' THEN 'Paid Social'
WHEN e.traffic_source = 'YouTube' THEN 'Video'
WHEN e.traffic_source = 'Email' THEN 'Email Marketing'
ELSE 'Organic'
END AS channel,
CASE
WHEN e.traffic_source = 'Adwords' AND MOD(e.id, 2) = 0 THEN 3.78
WHEN e.traffic_source = 'Adwords' THEN 2.64
WHEN e.traffic_source = 'Facebook' AND MOD(e.id, 2) = 0 THEN 1.85
WHEN e.traffic_source = 'Facebook' THEN 0.99
WHEN e.traffic_source = 'YouTube' THEN 0.85
WHEN e.traffic_source = 'Email' AND MOD(e.id, 2) = 0 THEN 0.12
WHEN e.traffic_source = 'Email' THEN 0.10
ELSE 0.00
END AS cpc_cost
FROM `thelook_graph.events` e;
2c. 歸因邊緣資料表
edge_influenced會將接觸點連結至受影響的訂單。並遵循以下四項規則:
- 如果同一位使用者在下單前 30 天內 (
created_at介於order time - 30 days和order time之間) 產生接觸點,該接觸點就會影響訂單。 - 系統會排除狀態為
Cancelled或Returned的訂單。 - 接觸點會依每個訂單 (
touchpoint_rank) 的時間排序;事件 ID 會打破平手,因此排名是確定的。 - 系統會預先計算每個接觸點的三個歸因權重:
first_touch_weight= 最早接觸點為 1.0,否則為 0.0last_touch_weight= 1.0 (最新接觸點),否則為 0.0linear_weight= 1 / (接觸點數量),因此每筆訂單的權重總和為 1.0
舉例來說,如果訂單有三個接觸點,則會獲得以下權重:
touchpoint_rank | first_touch_weight | last_touch_weight | linear_weight |
1 | 1.0 | 0.0 | 0.333333 |
2 | 0.0 | 0.0 | 0.333333 |
3 | 0.0 | 1.0 | 0.333333 |
在每個模式下,每筆訂單的權重總和都是 1.0,因此將委刊項的sale_price乘以權重再加總,絕不會重複計算收益。
CREATE OR REPLACE TABLE `thelook_graph.edge_influenced` AS
WITH ranked_touchpoints AS (
SELECT
t.touchpoint_id,
o.order_id,
t.campaign_name,
t.channel,
t.cpc_cost,
t.created_at AS event_timestamp,
o.created_at AS order_timestamp,
ROW_NUMBER() OVER (PARTITION BY o.order_id ORDER BY t.created_at ASC, t.touchpoint_id ASC) AS touchpoint_asc,
ROW_NUMBER() OVER (PARTITION BY o.order_id ORDER BY t.created_at DESC, t.touchpoint_id DESC) AS touchpoint_desc,
COUNT(*) OVER (PARTITION BY o.order_id) AS total_touchpoints
FROM `thelook_graph.orders` o
JOIN `thelook_graph.touchpoints` t
ON o.user_id = t.user_id
AND t.created_at <= o.created_at
AND t.created_at >= TIMESTAMP_SUB(o.created_at, INTERVAL 30 DAY)
WHERE o.status NOT IN ('Cancelled', 'Returned')
)
SELECT
touchpoint_id,
order_id,
campaign_name,
channel,
cpc_cost,
touchpoint_asc AS touchpoint_rank,
total_touchpoints,
ROUND(TIMESTAMP_DIFF(order_timestamp, event_timestamp, HOUR) / 24.0, 1) AS days_to_convert,
IF(touchpoint_asc = 1, 1.0, 0.0) AS first_touch_weight,
IF(touchpoint_desc = 1, 1.0, 0.0) AS last_touch_weight,
ROUND(1.0 / total_touchpoints, 6) AS linear_weight
FROM ranked_touchpoints;
驗證歸因邊緣
SELECT COUNT(*) AS attribution_edges
FROM `thelook_graph.edge_influenced`;
預期輸出內容:976,555。如果數字不同,請確認 created_at 已載入為 TIMESTAMP (使用邏輯類型旗標重新執行載入作業),且所有五個資料表的資料列數量都符合預期。
5. 宣告含有測量指標的屬性圖譜
屬性圖剖析
子句 | 用途 |
| 列出成為節點 (實體) 的資料表或檢視表。 |
| 用於識別節點的資料欄。系統會依據這個鍵簡化測量結果。 |
| 為節點提供查詢中使用的標籤 ( |
| 宣告屬於這個節點的匯總。 |
| 列出資料列會成為邊緣 (關係) 的資料表。同一個資料表可以同時顯示為節點和邊緣。 |
| 定義邊緣的起點和終點節點。 |
以下是您即將建立的圖表中的一個節點和一條邊,並附有註解:
-- A node: one row per campaign, keyed by campaign_name
`thelook_graph.marketing_campaigns` AS campaigns
KEY (campaign_name) -- unique key => AGG() dedupes on it
LABEL campaigns PROPERTIES (
campaign_name, channel, total_budget, target_roas,
MEASURE(SUM(total_budget)) AS total_campaign_budget -- a measure owned by this node
),
-- An edge: each touchpoint row points to the campaign that generated it
`thelook_graph.touchpoints` AS touchpoint_campaign
KEY (touchpoint_id)
SOURCE KEY (touchpoint_id) REFERENCES touchpoints (touchpoint_id) -- from a touchpoint...
DESTINATION KEY (campaign_name) REFERENCES campaigns (campaign_name) -- ...to its campaign
LABEL GENERATED_BY NO PROPERTIES
建立電子商務整合
在 BigQuery Studio 執行完整陳述式。其中宣告 6 個節點資料表 (含 10 個測量指標) 和 5 個邊緣資料表:
CREATE OR REPLACE PROPERTY GRAPH `thelook_graph.eCommerce_Integrated`
NODE TABLES (
-- 1. Marketing campaigns (upstream, coarse grain)
`thelook_graph.marketing_campaigns` AS campaigns
KEY (campaign_name)
LABEL campaigns PROPERTIES (
campaign_name,
channel,
total_budget,
target_roas,
MEASURE(SUM(total_budget)) AS total_campaign_budget
),
-- 2. Marketing touchpoints (web events tagged with campaigns)
`thelook_graph.touchpoints` AS touchpoints
KEY (touchpoint_id)
LABEL touchpoints PROPERTIES (
touchpoint_id,
user_id,
session_id,
campaign_name,
channel,
cpc_cost,
event_type,
browser,
created_at,
MEASURE(SUM(cpc_cost)) AS total_ad_spend,
MEASURE(COUNT(touchpoint_id)) AS total_clicks,
MEASURE(COUNT(DISTINCT user_id)) AS unique_reach
),
-- 3. Users
`thelook_graph.users` AS users
KEY (id)
LABEL users PROPERTIES (
id,
first_name,
last_name,
email,
age,
gender,
country,
traffic_source,
created_at,
MEASURE(COUNT(DISTINCT id)) AS total_users
),
-- 4. Orders
`thelook_graph.orders` AS orders
KEY (order_id)
LABEL orders PROPERTIES (
order_id,
user_id,
status,
created_at,
num_of_item,
MEASURE(COUNT(order_id)) AS total_orders
),
-- 5. Order items (the finest financial grain)
`thelook_graph.order_items` AS order_items
KEY (id)
LABEL order_items PROPERTIES (
id,
order_id,
user_id,
product_id,
sale_price,
status,
created_at,
MEASURE(SUM(sale_price)) AS gross_revenue,
MEASURE(COUNT(id)) AS total_items_sold
),
-- 6. Product catalog
`thelook_graph.products` AS products
KEY (id)
LABEL products PROPERTIES (
id,
cost,
category,
name,
brand,
retail_price,
department,
MEASURE(AVG(cost)) AS avg_cost,
MEASURE(AVG(retail_price)) AS avg_retail_price
)
)
EDGE TABLES (
-- Touchpoint -> Campaign
`thelook_graph.touchpoints` AS touchpoint_campaign
KEY (touchpoint_id)
SOURCE KEY (touchpoint_id) REFERENCES touchpoints (touchpoint_id)
DESTINATION KEY (campaign_name) REFERENCES campaigns (campaign_name)
LABEL GENERATED_BY NO PROPERTIES,
-- User -> Touchpoint
`thelook_graph.touchpoints` AS user_touchpoint
KEY (touchpoint_id)
SOURCE KEY (user_id) REFERENCES users (id)
DESTINATION KEY (touchpoint_id) REFERENCES touchpoints (touchpoint_id)
LABEL ENGAGED_WITH NO PROPERTIES,
-- Touchpoint -> Order, carrying the attribution weights
`thelook_graph.edge_influenced` AS edge_influenced
KEY (touchpoint_id, order_id)
SOURCE KEY (touchpoint_id) REFERENCES touchpoints (touchpoint_id)
DESTINATION KEY (order_id) REFERENCES orders (order_id)
LABEL INFLUENCED PROPERTIES (
campaign_name,
channel,
cpc_cost,
touchpoint_rank,
total_touchpoints,
days_to_convert,
first_touch_weight,
last_touch_weight,
linear_weight
),
-- Order item -> Order
`thelook_graph.order_items` AS item_order
KEY (id)
SOURCE KEY (id) REFERENCES order_items (id)
DESTINATION KEY (order_id) REFERENCES orders (order_id)
LABEL BELONGS_TO NO PROPERTIES,
-- Order item -> Product
`thelook_graph.order_items` AS item_product
KEY (id)
SOURCE KEY (id) REFERENCES order_items (id)
DESTINATION KEY (product_id) REFERENCES products (id)
LABEL IS_PRODUCT NO PROPERTIES
);
10 項指標,每項指標都在其所屬的精細程度宣告:
campaigns:total_campaign_budgettouchpoints:total_ad_spend,total_clicks,unique_reachusers:total_usersorders:total_ordersorder_items:gross_revenue、total_items_soldproducts:avg_cost、avg_retail_price
結構邊緣 (GENERATED_BY、ENGAGED_WITH、BELONGS_TO、IS_PRODUCT) 使用 NO PROPERTIES。只有 INFLUENCED 具有屬性,因為歸因權重是接觸點順序關係的屬性,而非任何節點的屬性。
驗證圖表
SELECT property_graph_name
FROM `thelook_graph.INFORMATION_SCHEMA.PROPERTY_GRAPHS`;
預期輸出內容:一列,eCommerce_Integrated。如果 CREATE 陳述式失敗,最常見的原因是前兩個步驟中缺少資料表或檢視表。
6. 使用 INFORMATION_SCHEMA 檢查測量指標
INFORMATION_SCHEMA.PROPERTY_GRAPHS 會在 property_graph_metadata_json 欄中以 JSON 格式公開圖表定義。nodeTables 陣列包含每個節點,每個節點的 labelAndProperties[0].properties 陣列會列出屬性,並以 expressionKind = "MEASURE" 標示測量指標。下列查詢會取消巢狀結構:
SELECT
JSON_VALUE(node_table_json, "$.name") AS node_table_name,
JSON_VALUE(prop_json, "$.name") AS measure_name,
JSON_VALUE(prop_json, "$.expression") AS measure_expression,
CONCAT("MEASURE<", JSON_VALUE(prop_json, "$.dataType.typeKind"), ">") AS measure_type
FROM `thelook_graph.INFORMATION_SCHEMA.PROPERTY_GRAPHS`,
UNNEST(JSON_EXTRACT_ARRAY(property_graph_metadata_json, "$.nodeTables")) AS node_table_json,
UNNEST(JSON_EXTRACT_ARRAY(node_table_json, "$.labelAndProperties[0].properties")) AS prop_json
WHERE JSON_VALUE(prop_json, "$.expressionKind") = "MEASURE"
ORDER BY node_table_name, measure_name;
預期輸出內容 (10 列):
node_table_name | measure_name | measure_expression | measure_type |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
在 BigQuery Studio 查看測量指標
- 在 BigQuery Studio 開啟「Explorer」面板。
- 依序展開專案、
thelook_graph資料集和「Graphs」。 - 按一下「eCommerce_Integrated」,然後開啟「List」分頁。
- 增加接觸點。實體資料欄 (
touchpoint_id、campaign_name、cpc_cost、...) 會列為DIMENSION,後面接著total_ad_spend、total_clicks和unique_reach,並標示為MEASURE,同時顯示推論類型。展開 edge_influenced,查看INFLUENCED邊緣帶有的三個歸因權重。
7. 查看問題:一般 SQL join 中的扇出
查詢圖表前,請先重現測量結果解決的問題。漏斗頂端的問題很簡單:每個廣告活動的預算、點擊次數和廣告支出為何?但輸入資料有兩種精細程度:marketing_campaigns 的預算 (每個廣告活動 1 列),以及 touchpoints 的點擊次數和支出 (240 萬列)。請按照目前大多數資料倉儲的做法,使用 join 函式回答:
SELECT
c.channel,
c.campaign_name,
SUM(c.total_budget) AS total_budget, -- wrong: repeated per touchpoint
COUNT(t.touchpoint_id) AS total_clicks, -- right: touchpoint grain
ROUND(SUM(t.cpc_cost), 2) AS total_ad_spend -- right: touchpoint grain
FROM `thelook_graph.marketing_campaigns` c
JOIN `thelook_graph.touchpoints` t
ON t.campaign_name = c.campaign_name
GROUP BY c.channel, c.campaign_name
ORDER BY total_ad_spend DESC;
預期輸出內容:
頻道 | campaign_name | total_budget | total_clicks | total_ad_spend |
付費搜尋 |
| $545,517,000,000 | 363,678 | $1,374,702.84 |
付費搜尋 |
| $400,045,800,000 | 363,678 | $960,109.92 |
付費社群活動 |
| $30,387,750,000 | 121,551 | $224,869.35 美元 |
影片 |
| $53,192,700,000 | 241,785 | $205,517.25 |
付費社群活動 |
| $18,278,700,000 | 121,858 | $120,639.42 |
電子郵件行銷 |
| $40,838,925,000 | 544,519 | $65,342.28 美元 |
電子郵件行銷 |
| $32,677,800,000 | 544,630 | $54,463.00 |
自然 |
| $3,041,650,000 | 121,666 | $0.00 美元 |
為什麼三欄中有兩欄仍正確
total_clicks 和 total_ad_spend 正確,因為 touchpoint_id 和 cpc_cost 位於要加總的資料列層級:每個接觸點一個值,每個資料列一個接觸點。total_budget 是廣告活動層級的值,會標記在每個接觸點資料列上,因此彙整會將一個數字轉換成數十萬個副本。這就是笛卡兒扇出,而且會隨著每次躍點而複合:將彙整範圍擴大至訂單和訂單項目,相同的 $60,000 美元會落在超過一百萬列。
為什麼常見的解決方法不適用
ANY_VALUE(c.total_budget)會挑選一個副本,但只有在GROUP BY保持在廣告活動層級時才有效。如果改為依管道分組,系統會默默保留一個廣告活動的預算,並捨棄其餘預算。- 每個精細程度都有獨立的 CTE 是正確的,但每個新指標都需要自己的 CTE 和彙整,而且無法防止後續編輯彙整錯誤的指標。
- 只要有兩個廣告活動共用預算,
SUM(DISTINCT c.total_budget)就會出錯。
測量指標可從來源解決問題:預算匯總會在 campaigns 節點上宣告一次,無論查詢加入其他什麼內容,BigQuery 都會以該精細程度評估。請記住 $32,677,800,000 這個數字,在下一個步驟中,您將透過圖表執行相同的評量表。
8. 應用實例 1:漏斗頂端和漏斗底端匯總 (GRAPH_EXPAND)
GRAPH_EXPAND 的運作方式
GRAPH_EXPAND("graph", start_node => "touchpoints")會為每個touchpoints節點傳回一個資料列,並與其連結的節點彙整,這裡為campaigns(透過GENERATED_BY) 和users(透過ENGAGED_WITH)。- 每個屬性和測量指標都會顯示為名為
的資料欄,例如_ campaigns_channel、campaigns_total_campaign_budget和touchpoints_total_clicks。 AGG(會在每個群組中,針對每個不重複的節點索引鍵評估一次測量指標。因此,即使廣告活動列在 363,678 個接觸點列中重複出現,) AGG(campaigns_total_campaign_budget)也只會加總每個廣告活動的預算一次。- 其他部分則為標準 SQL (
GROUP BY、ORDER BY、ROUND),因此商業智慧工具可以直接發出這些查詢。
查詢 1A:漏斗頂端行銷評量表
在先前的步驟中,一般彙整會根據點擊次數,提高每個廣告活動的預算。現在請透過圖表回答相同的問題。在結構上,GRAPH_EXPAND 會取代 FROM 子句中的 join,AGG() 則會取代 SUM() 和 COUNT():
SELECT
campaigns_channel AS channel,
campaigns_campaign_name AS campaign_name,
AGG(campaigns_total_campaign_budget) AS total_budget,
AGG(touchpoints_total_clicks) AS total_clicks,
AGG(touchpoints_unique_reach) AS unique_reach,
ROUND(AGG(touchpoints_total_ad_spend), 2) AS total_ad_spend,
ROUND(AGG(campaigns_total_campaign_budget) - AGG(touchpoints_total_ad_spend), 2) AS remaining_budget,
ROUND(AGG(touchpoints_total_ad_spend) / NULLIF(AGG(touchpoints_total_clicks), 0), 2) AS effective_avg_cpc
FROM GRAPH_EXPAND("thelook_graph.eCommerce_Integrated", start_node => "touchpoints")
GROUP BY channel, campaign_name
ORDER BY total_ad_spend DESC;
預期輸出內容:
頻道 | campaign_name | total_budget | total_clicks | unique_reach | total_ad_spend | remaining_budget | effective_avg_cpc |
付費搜尋 |
| $1,500,000 | 363,678 | 39,695 | $1,374,702.84 | $125,297.16 | 新臺幣 $113.4 元 |
付費搜尋 |
| $1,100,000 | 363,678 | 39,695 | $960,109.92 | $139,890.08 美元 | $2.64 |
付費社群活動 |
| $250,000 | 121,551 | 16,182 | $224,869.35 美元 | $25,130.65 | NT$55.5 |
影片 |
| $220,000 | 241,785 | 16,161 | $205,517.25 | $14,482.75 | $0.85 |
付費社群活動 |
| $150,000 | 121,858 | 16,182 | $120,639.42 | $29,360.58 | $0.99 美元 |
電子郵件行銷 |
| $75,000 | 544,519 | 52,049 | $65,342.28 美元 | $9,657.72 | $0.12 美元 |
電子郵件行銷 |
| $60,000 | 544,630 | 52,049 | $54,463.00 | $5,537.00 | $0.10 美元 |
自然 |
| $25,000 | 121,666 | 8,618 | $0.00 美元 | $25,000.00 美元 | $0.00 美元 |
檢查:Q4_Email_VIP_Weekly_Drop 的 total_budget 為 $60,000,而非一般彙整產生的 $32,677,800,000。AGG() 只會計算一次廣告活動預算,即使廣告活動資料列仍會在每個接觸點重複顯示,而 total_clicks 仍會計算所有 544,630 個接觸點。
查詢 1B:漏斗底部宣傳匯總
在同一圖表中傳遞 start_node => "order_items",向 orders (BELONGS_TO) 和 products (IS_PRODUCT) 展開:
SELECT
products_department AS department,
products_category AS category,
AGG(orders_total_orders) AS distinct_orders,
AGG(order_items_total_items_sold) AS items_sold,
ROUND(AGG(order_items_gross_revenue), 2) AS gross_revenue,
ROUND(AGG(products_avg_cost), 2) AS avg_unit_cost,
ROUND(AGG(products_avg_retail_price), 2) AS avg_retail_price
FROM GRAPH_EXPAND("thelook_graph.eCommerce_Integrated", start_node => "order_items")
GROUP BY department, category
ORDER BY gross_revenue DESC
LIMIT 5;
預期輸出內容:
部門 | category | distinct_orders | items_sold | gross_revenue | avg_unit_cost | avg_retail_price |
男性 |
| 5,564 | 5,713 | $852,464.61 | $65.94 | $149.40 美元 |
男性 |
| 7,370 | 7,679 | $779,004.17 | $53.80 | $101.16 |
男性 |
| 4,926 | 5,041 | $642,783.10 | $50.74 | $126.37 |
男性 |
| 6,660 | 6,869 | $528,344.51 | $38.83 美元 | $77.59 |
女性 |
| 3,258 | 3,323 | $470,456.28 | $63.74 | $141.55 |
檢查:男性的 Outerwear & Coats,distinct_orders (5,564) 小於 items_sold (5,713)。AGG(orders_total_orders) 依order_id簡化多商品購物籃,而AGG(order_items_total_items_sold)則計算每個委刊項。
9. 用途 2:多接觸點歸因分析比較 (GRAPH_TABLE)
解讀 GQL 模式
GRAPH_TABLE 會在 SQL FROM 子句中嵌入圖表模式。這項查詢的模式如下:
(t:touchpoints)-[i:INFLUENCED]->(o:orders)<-[:BELONGS_TO]-(oi:order_items)
(t:touchpoints)會比對標籤為touchpoints的節點,並將其繫結至變數t。-[i:INFLUENCED]->會沿著INFLUENCED邊緣的宣告方向 (接觸點 ➔ 順序) 進行,並將邊緣繫結至i,以便您讀取i.linear_weight。(o:orders)是受影響的訂單。<-[:BELONGS_TO]-(oi:order_items)會比對指向訂單「內部」的BELONGS_TO邊緣 (箭頭指向左側):每個委刊項oi都屬於訂單o。由於您不需要邊緣的任何屬性,因此邊緣不會取得變數。COLUMNS (...)會將節點和邊緣屬性投影至一般資料欄,之後SUM和GROUP BY就能照常運作。
查詢
SELECT
campaign_name,
channel,
ROUND(SUM(sale_price * first_touch_weight), 2) AS first_touch_revenue,
ROUND(SUM(sale_price * last_touch_weight), 2) AS last_touch_revenue,
ROUND(SUM(sale_price * linear_weight), 2) AS linear_revenue
FROM GRAPH_TABLE(`thelook_graph.eCommerce_Integrated`
MATCH (t:touchpoints)-[i:INFLUENCED]->(o:orders)<-[:BELONGS_TO]-(oi:order_items)
COLUMNS (
t.campaign_name AS campaign_name,
t.channel AS channel,
oi.sale_price,
i.first_touch_weight,
i.last_touch_weight,
i.linear_weight
)
)
GROUP BY campaign_name, channel
ORDER BY linear_revenue DESC;
預期輸出內容:
campaign_name | 頻道 | first_touch_revenue | last_touch_revenue | linear_revenue |
| 電子郵件行銷 | $1,844,969.34 | $1,852,985.64 美元 | $1,836,711.27 |
| 電子郵件行銷 | $1,846,318.54 | $1,818,126.95 | $1,836,242.50 |
| 付費搜尋 | $1,203,174.40 | $1,203,055.84 | $1,208,564.90 |
| 付費搜尋 | $1,204,866.84 | $1,204,632.74 | $1,207,724.05 |
| 影片 | $809,437.33 | $821,840.02 | $814,035.10 |
| 自然 | NT$12,287,966 | $420,458.99 | $412,996.24 |
| 付費社群活動 | NT$12,327,008 | $401,289.08 | $407,354.92 |
| 付費社群活動 | $398,192.90 | NT$12,152,077 | $403,816.94 |
檢查:將 linear_revenue 欄中的值相加 (或移除 GROUP BY)。每個模式的總和都是 $8,127,445.92 美元,因為每筆訂單的權重總和為 1.0,收益只會在廣告活動之間重新分配,不會增加或減少。
數據會說話
- 在所有模式中,透過電子郵件培養待開發客戶。兩個電子郵件廣告活動各歸因約 $184 萬美元。
- 開發潛在客戶與成交。
Q4_TikTok_Prospecting_GenZ在「最初接觸」模式下獲得的功勞 ($410,900.27 美元) 高於「最終接觸」模式 ($401,289.08 美元),這與漏斗頂端角色的特性一致。Q4_Meta_IG_Retargeting($405,069.24 美元) 和Q4_YouTube_Video_Awareness($821,840.02 美元) 在最終接觸模式下獲得收益,與最終接觸角色一致。
10. 用途 3:4 跳獲利能力和毛利率百分比 (GRAPH_TABLE)
查詢
模式會加上 -[:IS_PRODUCT]->(p:products),達到每個委刊項的目錄費用:
SELECT
campaign_name,
channel,
ROUND(SUM(sale_price * linear_weight), 2) AS attributed_revenue,
ROUND(SUM(cost * linear_weight), 2) AS attributed_cogs,
ROUND(SUM((sale_price - cost) * linear_weight), 2) AS gross_profit,
ROUND(SAFE_DIVIDE(SUM((sale_price - cost) * linear_weight), SUM(sale_price * linear_weight)) * 100, 2) AS gross_margin_pct
FROM GRAPH_TABLE(`thelook_graph.eCommerce_Integrated`
MATCH (t:touchpoints)-[i:INFLUENCED]->(o:orders)<-[:BELONGS_TO]-(oi:order_items)-[:IS_PRODUCT]->(p:products)
COLUMNS (
t.campaign_name AS campaign_name,
t.channel AS channel,
oi.sale_price,
p.cost,
i.linear_weight
)
)
GROUP BY campaign_name, channel
ORDER BY gross_profit DESC;
預期輸出內容:
campaign_name | 頻道 | attributed_revenue | attributed_cogs | gross_profit | gross_margin_pct |
| 電子郵件行銷 | $1,836,711.27 美元 | $883,586.30 美元 | $953,124.97 | 51.89% |
| 電子郵件行銷 | $1,836,242.50 | $883,678.75 美元 | $952,563.75 | 51.88% |
| 付費搜尋 | $1,208,564.90 | $581,095.89 | $627,469.01 | 51.92% |
| 付費搜尋 | $1,207,724.05 | $580,774.28 | $626,949.77 | 51.91% |
| 影片 | $814,035.10 | $391,917.60 | $422,117.50 | 51.85% |
| 自然 | $412,996.24 | $199,002.75 | $213,993.48 | 51.81% |
| 付費社群活動 | $407,354.92 美元 | $195,816.75 美元 | $211,538.17 | 51.93% |
| 付費社群活動 | $403,816.94 | $194,039.16 | $209,777.78 | 51.95% |
檢查: attributed_revenue 與用途 2 的 linear_revenue 完全相符。在 products 中新增躍點不會改變收益,因為每個訂單項目都只有一項產品。
額外練習:4 個躍點的類別相似度
按產品類別劃分相同路徑,查看哪些廣告活動銷售某個類別,以及購物者需要多久時間才能完成轉換:
SELECT
category AS product_category,
channel AS marketing_channel,
campaign_name,
COUNT(DISTINCT order_id) AS orders_count,
ROUND(SUM(sale_price * linear_weight), 2) AS attributed_sales,
ROUND(AVG(days_to_convert), 1) AS avg_days_to_convert
FROM GRAPH_TABLE(
`thelook_graph.eCommerce_Integrated`
MATCH (t:touchpoints)-[i:INFLUENCED]->(o:orders)<-[:BELONGS_TO]-(oi:order_items)-[:IS_PRODUCT]->(p:products)
COLUMNS (
t.campaign_name AS campaign_name,
t.channel AS channel,
p.category AS category,
o.order_id AS order_id,
oi.sale_price AS sale_price,
i.linear_weight AS linear_weight,
i.days_to_convert AS days_to_convert
)
)
WHERE category = 'Outerwear & Coats'
GROUP BY category, channel, campaign_name
ORDER BY attributed_sales DESC;
預期輸出內容:
product_category | marketing_channel | campaign_name | orders_count | attributed_sales | avg_days_to_convert |
| 電子郵件行銷 |
| 4,178 | $226,054.71 | 0.6 |
| 電子郵件行銷 |
| 4,186 | $224,058.77 | 0.6 |
| 付費搜尋 |
| 3,131 | $151,458.01 | 0.6 |
| 付費搜尋 |
| 3,138 | $150,364.63 | 0.6 |
| 影片 |
| 1,246 | $97,937.94 | 0.6 |
| 自然 |
| 666 | $48,987.74 | 0.5 |
| 付費社群活動 |
| 1,158 | $48,378.34 | 0.6 |
| 付費社群活動 |
| 1,156 | $47,820.41 美元 | 0.6 |
11. 應用實例 4:顧客歷程對應 (ISO GQL)
查詢 4A:追蹤一位購物者的轉換路徑
購物者小莫 (user_id = 21) 下了兩筆訂單。這項查詢會從使用者開始,依序追蹤 ENGAGED_WITH 到接觸點,然後追蹤 INFLUENCED 到接觸點促成的訂單:
GRAPH `thelook_graph.eCommerce_Integrated`
MATCH (u:users)-[:ENGAGED_WITH]->(t:touchpoints)-[i:INFLUENCED]->(o:orders)
WHERE u.id = 21
RETURN
u.id AS user_id,
u.first_name,
t.campaign_name,
t.channel,
t.event_type,
i.touchpoint_rank,
i.linear_weight,
o.order_id
ORDER BY o.order_id, i.touchpoint_rank
LIMIT 10;
預期輸出內容:
user_id | first_name | campaign_name | 頻道 | event_type | touchpoint_rank | linear_weight | order_id |
21 | Maurice |
| 電子郵件行銷 |
| 1 | 0.2 | 27 |
21 | Maurice |
| 電子郵件行銷 |
| 2 | 0.2 | 27 |
21 | Maurice |
| 電子郵件行銷 |
| 3 | 0.2 | 27 |
21 | Maurice |
| 電子郵件行銷 |
| 4 | 0.2 | 27 |
21 | Maurice |
| 電子郵件行銷 |
| 5 | 0.2 | 27 |
21 | Maurice |
| 付費搜尋 |
| 1 | 0.2 | 28 |
21 | Maurice |
| 付費搜尋 |
| 2 | 0.2 | 28 |
21 | Maurice |
| 付費搜尋 |
| 3 | 0.2 | 28 |
21 | Maurice |
| 付費搜尋 |
| 4 | 0.2 | 28 |
21 | Maurice |
| 付費搜尋 |
| 5 | 0.2 | 28 |
檢查:每筆訂單都有 5 個與 linear_weight = 0.2 相關的接觸點,且 event_type 序列 (home ➔ department ➔ product ➔ cart ➔ purchase) 看起來像瀏覽工作階段。訂單 27 是由電子郵件促成,訂單 28 則是由付費搜尋促成。
查詢 4B:以圖形物件形式傳回路徑
將整個模式繫結至路徑變數 p,並使用 TO_JSON() 序列化。結果會將路徑上的每個節點和邊緣,以單一 JSON 值的形式傳送,適合用於將子圖傳送至應用程式或 AI 代理,BigQuery Studio 的圖表視覺化功能也會讀取這項資訊:
GRAPH `thelook_graph.eCommerce_Integrated`
MATCH p = (u:users)-[:ENGAGED_WITH]->(t:touchpoints)-[:INFLUENCED]->(o:orders)
WHERE u.id = 21
RETURN TO_JSON(p) AS path
LIMIT 10;
查詢完成後,在查詢結果窗格中,選取「結果」旁的「圖表」分頁標籤。BigQuery Studio 會繪製 Maurice 的使用者節點,並透過 ENGAGED_WITH 邊緣連結至他的 10 個接觸點,每個接觸點則透過 INFLUENCED 邊緣連結至促成的訂單。按一下 users 節點,查看其屬性 (包括 first_name: Maurice) 和 10 個鄰近節點。

12. 應用實例 5:綜合高階主管廣告投資報酬率評量表
查詢
WITH marketing_funnel AS (
-- 1. Top-of-funnel measures at their own grain (all 2.4M touchpoints)
SELECT
campaigns_channel AS channel,
campaigns_campaign_name AS campaign_name,
AGG(campaigns_total_campaign_budget) AS total_budget,
AGG(touchpoints_total_clicks) AS total_clicks,
AGG(touchpoints_unique_reach) AS unique_reach,
ROUND(AGG(touchpoints_total_ad_spend), 2) AS total_ad_spend,
ROUND(AGG(campaigns_total_campaign_budget) - AGG(touchpoints_total_ad_spend), 2) AS remaining_budget,
ROUND(AGG(touchpoints_total_ad_spend) / NULLIF(AGG(touchpoints_total_clicks), 0), 2) AS effective_avg_cpc
FROM GRAPH_EXPAND("thelook_graph.eCommerce_Integrated", start_node => "touchpoints")
GROUP BY channel, campaign_name
),
sales_attribution AS (
-- 2. 4-hop profit attribution over converting paths only
SELECT
campaign_name,
ROUND(SUM(sale_price * linear_weight), 2) AS attributed_revenue,
ROUND(SUM(cost * linear_weight), 2) AS attributed_cogs,
ROUND(SUM((sale_price - cost) * linear_weight), 2) AS gross_profit
FROM GRAPH_TABLE(`thelook_graph.eCommerce_Integrated`
MATCH (t:touchpoints)-[i:INFLUENCED]->(o:orders)<-[:BELONGS_TO]-(oi:order_items)-[:IS_PRODUCT]->(p:products)
COLUMNS (
t.campaign_name AS campaign_name,
oi.sale_price,
p.cost,
i.linear_weight
)
)
GROUP BY campaign_name
)
-- 3. Join the two views of the same graph
SELECT
m.channel,
m.campaign_name,
m.total_budget,
m.total_ad_spend,
m.remaining_budget,
m.effective_avg_cpc,
s.attributed_revenue,
s.gross_profit,
ROUND(s.attributed_revenue / NULLIF(m.total_ad_spend, 0), 2) AS roas_on_spend,
ROUND(s.attributed_revenue / NULLIF(m.total_budget, 0), 2) AS roas_on_budget,
ROUND(SAFE_DIVIDE(s.gross_profit, s.attributed_revenue) * 100, 2) AS gross_margin_pct
FROM marketing_funnel m
JOIN sales_attribution s ON m.campaign_name = s.campaign_name
ORDER BY s.gross_profit DESC;
預期輸出內容:
頻道 | campaign_name | total_budget | total_ad_spend | remaining_budget | effective_avg_cpc | attributed_revenue | gross_profit | roas_on_spend | roas_on_budget | gross_margin_pct |
電子郵件行銷 |
| $60,000 美元 | $54,463.00 | $5,537.00 | $0.10 美元 | $1,836,711.27 美元 | $953,124.97 | 33.72 | 30.61 | 51.89% |
電子郵件行銷 |
| $75,000 | $65,342.28 美元 | $9,657.72 | $0.12 美元 | $1,836,242.50 | $952,563.75 | 28.10 | 24.48 | 51.88% |
付費搜尋 |
| $1,500,000 | $1,374,702.84 | $125,297.16 | 新臺幣 $113.4 元 | $1,208,564.90 | $627,469.01 | 0.88 | 0.81 | 51.92% |
付費搜尋 |
| $1,100,000 美元 | $960,109.92 | $139,890.08 美元 | $2.64 | $1,207,724.05 | $626,949.77 | 1.26 | 1.10 | 51.91% |
影片 |
| $220,000 | $205,517.25 | $14,482.75 | $0.85 | $814,035.10 | $422,117.50 | 3.96 | 3.70 | 51.85% |
自然 |
| $25,000 美元 | $0.00 美元 | $25,000.00 美元 | $0.00 美元 | $412,996.24 | $213,993.48 | NULL | 16.52 | 51.81% |
付費社群活動 |
| $150,000 | $120,639.42 | $29,360.58 | $0.99 美元 | $407,354.92 美元 | $211,538.17 | 3.38 | 2.72 | 51.93% |
付費社群活動 |
| $250,000 | $224,869.35 美元 | $25,130.65 | NT$55.5 | $403,816.94 | $209,777.78 | 1.80 | 1.62 | 51.95% |
檢查:roas_on_spend 的 Q4_Email_VIP_Weekly_Drop 為 33.72 ($1,836,711.27 ÷ $54,463.00)。Organic_Search_SEO 顯示 NULL,因為廣告支出為 $0 美元,NULLIF 可避免除以零。
13. 選用:BigQuery 和 Gemini Enterprise 中的對話式數據分析代理
+---------------------------------------------------+
| BigQuery Studio: Agents |
| (knowledge source: thelook_graph.eCommerce_Integrated,|
| 10 measures) |
+-------------------------┬-------------------------+
│ 1. Create and publish the data agent
▼
+---------------------------------------------------+
| Conversational Analytics data agent |
| (Marketing-Attribution-Agent) |
+-------------------------┬-------------------------+
│ 2. Import the agent into Gemini Enterprise
▼
+---------------------------------------------------+
| Gemini Enterprise chat |
| (business users ask questions in natural language)|
+---------------------------------------------------+
啟用 API 和角色
除了 BigQuery 之外,資料代理還需要 Gemini 資料分析、Gemini for Google Cloud 和 Knowledge Catalog API。在 Cloud Shell 執行以下指令:
gcloud services enable \
geminidataanalytics.googleapis.com \
cloudaicompanion.googleapis.com \
dataplex.googleapis.com \
--project=${PROJECT_ID}
如要建立代理,您必須具備 Gemini Data Analytics 資料代理建立者角色 (roles/geminidataanalytics.dataAgentCreator);與代理對話的使用者則須具備 Gemini Data Analytics 資料代理使用者角色 (roles/geminidataanalytics.dataAgentUser)。詳情請參閱「建立資料代理」。
在 BigQuery 建立及發布代理
- 在 Google Cloud 控制台中,依序前往「BigQuery」 >「代理」,然後選取「代理目錄」分頁標籤。
- 點選「建立代理」,然後設定下列項目:
- 代理名稱:
Marketing-Attribution-Agent - 代理說明:
Answers questions about marketing campaigns, ad spend, multi-touch attribution, ROAS, and customer conversion journeys.
- 代理名稱:
- 在「知識來源」下方,點選「新增來源」,然後選取屬性圖
thelook_graph.eCommerce_Integrated。請附加圖表本身,而非僅附加資料集,因為評估指標是在圖表上定義。 - 按一下 [發布]。在「發布管道」窗格的「其他管道」下方,選擇 Gemini Enterprise 存取代理的方式:
- 如果 BigQuery 和 Gemini Enterprise 位於同一個專案,請在「Agent Registry」部分選取「註冊這個代理」。
- 否則,請在「透過 A2A (Agent2Agent) 整合」中,點選「複製 JSON」複製代理資訊卡。

- 按一下「發布」 (或「發布更新」)。
將代理匯入 Gemini Enterprise
- 在 Gemini Enterprise 中開啟應用程式,然後依序前往「代理」 >「新增代理」。
- 在「Import agent」步驟中,貼上代理資訊卡 JSON,然後按一下「Preview Agent Details」。確認代理名稱為
Marketing-Attribution-Agent,然後點選「Next」(下一步)。
- 在「Agent authorization」步驟中,接受預先填入的 OAuth 設定 (或輸入貴機構的設定),然後按一下「Finish」。

驗證代理
開啟與 Marketing-Attribution-Agent 的對話,並詢問:
Q4_Search_Generic_Audio 的廣告總支出是多少?請按年份細分,並顯示圖表。
- 預期結果:總計 $1,374,702.84,也就是該廣告活動的
total_ad_spend測量指標值 (請參閱查詢 1A)。代理也會傳回年度細目,通常會以長條圖呈現。 - 如果數字達到數十億:代表代理並未使用圖表,而是彙整原始資料表。確認已附加屬性圖
eCommerce_Integrated做為知識來源,發布更新,然後再次詢問。

試試其他提示
- 「顯示使用者 21 的轉換歷程。請加入使用者名字,並針對他們下達的每筆訂單,依序排列影響訂單的接觸點,並列出廣告活動名稱、管道、事件類型和線性權重。然後總結每筆訂單是由哪個管道促成。」服務專員應說出 Maurice 的名字,並說明他的兩筆訂單:訂單 27 前有五個電子郵件行銷接觸點,訂單 28 前有五個付費搜尋接觸點,每個接觸點的權重為 0.2。

- 「根據 thelook_graph.eCommerce_Integrated 圖表,建立廣告活動獲利能力排行榜。針對每個廣告活動報表管道,列出 total_ad_spend (使用圖表的 total_ad_spend 測量指標,而非透過彙整得出的 cpc_cost 總和)、依 linear_weight 加權的 attributed_revenue 和 gross_profit,以及 roas_on_spend。Rank by gross_profit and draw a bar chart of roas_on_spend.代理應將
Q4_Email_VIP_Weekly_Drop(毛利 $953,124.97 美元,廣告投資報酬率 33.72 倍) 和Q4_Email_Cart_Abandonment($952,563.75 美元,28.10 倍) 排在最前面,符合用途 5。如果total_ad_spend值與查詢 1A 不符,代表代理從原始資料表重新衍生支出,請重複操作說明,使用測量指標。
- 「Q4_Search_Generic_Audio 的剩餘預算有多少?平均單次點擊出價是多少?」預期:剩餘 $125,297.16 美元,單次點擊出價為 $3.78 美元。
14. 決策指南和清理
各運算子的使用時機
做法 | 使用時機 | 原因 |
單一資料表的純 SQL | 您在資料欄所屬資料表的精細程度匯總資料欄 (例如 | 沒有 join,因此不會重複資料列。 |
在多資料表彙整中,使用純 SQL | 避免用於 1:N 或 N:M 關係。 | 粗略值會在每個彙整資料列重複,因此單一廣告活動預算會按每次點擊和委刊項加總一次。 |
| 您需要多躍點路徑、邊緣篩選器或葉粒加權總和,例如 | 系統會針對每個相符路徑評估路徑層級運算式。由於每筆訂單的權重總和為 1.0,因此收益和費用不會受到影響。 |
| 您需要多精細程度匯總,在適合商業智慧的 SQL 中混合粗略測量 ( | 每項測量指標都會在宣告的精細程度進行評估,因此展開不會導致指標膨脹。 |
清除所用資源
為避免在完成後產生費用,請在 BigQuery Studio 中刪除圖表和資料集:
DROP PROPERTY GRAPH IF EXISTS `thelook_graph.eCommerce_Integrated`;
DROP SCHEMA IF EXISTS `thelook_graph` CASCADE;
接著,在 Cloud Shell 中刪除預留項目指派作業和預留項目。指派作業 ID 是由 BigQuery 產生,因此請先查詢:
# 1. Look up the assignment ID
ASSIGNMENT_ID=$(bq ls --reservation_assignment \
--project_id=${PROJECT_ID} --location=${REGION} --format=json \
| python3 -c 'import json,sys; print(json.load(sys.stdin)[0]["name"].split("/")[-1])')
echo "Deleting assignment ${ASSIGNMENT_ID}"
# 2. Delete the assignment, then the reservation
bq rm --reservation_assignment \
--project_id=${PROJECT_ID} \
--location=${REGION} \
${RESERVATION_NAME}.${ASSIGNMENT_ID}
bq rm --reservation \
--project_id=${PROJECT_ID} \
--location=${REGION} \
${RESERVATION_NAME}
# 3. Confirm nothing is left
bq ls --reservation --project_id=${PROJECT_ID} --location=${REGION}
預期的最終輸出內容:No reservations found.
如果您建立了選用的資料代理,請依序前往「BigQuery」 >「代理」 >「代理目錄」刪除,並從 Gemini Enterprise 應用程式中移除。
15. 恭喜
您在 BigQuery 中根據 thelook_ecommerce 快照建立了行銷歸因和廣告投資報酬率圖表,並使用測量指標匯總預算、支出和收益,而不是透過彙整重複計算。
完成事項
- 就地建立屬性圖模型:
thelook_graph.eCommerce_Integrated、6 個節點、5 個邊、10 項測量指標,沒有資料複製到圖形資料庫。 - 透過
INFORMATION_SCHEMA.PROPERTY_GRAPHS檢查測量指標。 - 使用一般彙整重現笛卡兒扇出:$60,000 美元的預算總和為 $32,677,800,000 美元。
- 使用
GRAPH_EXPAND和AGG()匯總漏斗兩端,讓每項指標保持在各自的精細程度。 - 使用
GRAPH_TABLE比較最初接觸、最終接觸和線性歸因,並確認總金額 ($8,127,445.92 美元) 在各模式中均不變。 - 計算 4 躍點毛利和毛利率 (每個廣告活動約 51.9%),以達到產品成本。
- 追蹤購物者的歷程:使用純 ISO GQL 追蹤購物者的歷程,並在 BigQuery Studio 中以圖表呈現。
- 將兩種查詢樣式合併為一份廣告投資報酬率主管評量表。
- (選用) 在圖表上建立對話式數據分析代理的基準,並發布至 Gemini Enterprise。