您可以使用 Google Analytics Data API v1 產生資料透視表。資料透視表是一種資料摘要工具,可透過一或多個維度透視 (旋轉) 資料,重新排列資料表中的資訊,以視覺化方式呈現資料。
舉例來說,請參考下列原始資料表:

您可以使用這項資料建立資料透視表,依瀏覽器細分工作階段資料,並選取國家/地區和語言維度做為其他資料透視表。

與 Core 報表共用的功能
在許多共用功能中,透視報表要求與核心報表要求具有相同的語意。舉例來說,分頁、維度篩選器和使用者屬性在透視報表中的行為與核心報表相同。本指南著重說明資料透視報表功能。如要熟悉 Data API v1 的核心報表功能,請參閱報表基本概念指南和進階用途指南。
透視報表記錄方式
Data API v1 支援下列報表方法中的資料透視功能:
runPivotReport:這個方法會傳回 Google Analytics 事件資料的自訂透視報表。每個透視表都會說明報表回應中可見的維度欄和列。
batchRunPivotReports:這是
runPivotReport方法的批次版本,可讓您使用單一 API 呼叫產生多份報表。
選取報表實體
Data API v1 的所有方法都必須在網址要求路徑中,以 properties/GA_PROPERTY_ID 的形式指定 Google Analytics 資源 ID,例如:
POST https://analyticsdata.googleapis.com/v1beta/properties/GA_PROPERTY_ID:runPivotReport
系統會根據指定 Google Analytics 資源中收集的 Google Analytics 事件資料,產生報表。
如果您使用 Data API 用戶端程式庫,就不需要手動操作要求網址路徑。大多數 API 用戶端都會提供 property 參數,該參數預期會收到 properties/GA_PROPERTY_ID 格式的字串。如需使用用戶端程式庫的範例,請參閱快速入門指南。
透視報表要求
如要建構包含資料透視表的要求,請使用 runPivotReport 或 batchRunPivotReports 方法。
如要要求透視資料,您可以建構 RunPivotReportRequest 物件。建議您先使用下列要求參數:
- dateRanges 欄位中的有效項目。
- dimensions 欄位中至少有一個有效項目。
- metrics 欄位中至少有一個有效項目。
- pivots 欄位中至少有兩個有效的資料透視項目。
以下是包含建議欄位的要求範例:
HTTP
POST https://analyticsdata.googleapis.com/v1beta/properties/GA_PROPERTY_ID:runPivotReport
{
"dateRanges": [{ "startDate": "2020-09-01", "endDate": "2020-09-15" }],
"dimensions": [
{ "name": "browser" },
{ "name": "country" },
{ "name": "language" }
],
"metrics": [{ "name": "sessions" }],
"pivots": [
{
"fieldNames": [
"browser"
],
"limit": 5
},
{
"fieldNames": [
"country"
],
"limit": 250
},
{
"fieldNames": [
"language"
],
"limit": 15
}
]
}
資料透視
在要求主體的 pivot 欄位中使用 Pivot 物件,定義報表透視表。每個 Pivot 都會說明報表回應中可見的維度欄和列。
Data API v1 支援多個資料透視,只要每個資料透視的 limit 參數乘積不超過 100,000 即可。
下列程式碼片段示範如何使用 pivots,依國家/地區建立工作階段計數報表,並以 browser 維度為透視。請注意,查詢如何使用 orderBys 欄位進行排序,並使用 limit 和 offset 欄位實作分頁。
"pivots": [
{
"fieldNames": [
"country"
],
"limit": 250,
"orderBys": [
{
"dimension": {
"dimensionName": "country"
}
}
]
},
{
"fieldNames": [
"browser"
],
"offset": 3,
"limit": 3,
"orderBys": [
{
"metric": {
"metricName": "sessions"
},
"desc": true
}
]
}
],
...
尺寸
維度會描述及分組網站或應用程式的事件資料。舉例來說,city 維度會指出每個事件的來源城市 (「巴黎」或「紐約」)。在報表要求中,您可以指定零或多個維度。
維度必須在要求主體的 dimensions 欄位中定義。如要在報表中顯示這些維度,也必須在 Pivot 物件的 fieldNames 欄位中列出。如果維度未用於透視查詢的任何透視,就不會顯示在報表中。並非每個維度都必須出現在資料透視表的 fieldNames 中。維度只能用於篩選器,不能用於任何資料透視表的 fieldNames。
下列程式碼片段示範如何使用 dimension 和 fieldNames 欄位,建立包含 browser、country 和 language 樞紐的表格:
"pivots": [
{
"fieldNames": [
"browser"
],
"limit": 5,
"orderBys": [
{
"metric": {
"metricName": "sessions"
},
"desc": true
}
]
},
{
"fieldNames": [
"country"
],
"limit": 250,
"orderBys": [
{
"dimension": {
"dimensionName": "country"
}
}
]
},
{
"fieldNames": [
"language"
],
"limit": 10
}
],
指標
指標是網站或應用程式事件資料的量化評估。在報表要求中,您可以指定一或多個指標。如需可在要求中指定的 API 指標名稱完整清單,請參閱「API 指標」。
在資料透視報表要求中,指標是使用要求主體的 metrics 欄位定義,這與核心報表方法類似。
以下範例指定將工作階段計數做為報表中的指標值:
"metrics": [
{
"name": "sessions"
}
],
指標匯總
使用 Pivot 物件的 metricAggregations 欄位,計算每個資料透視的匯總指標值。
只有在要求中指定 metricAggregations 欄位時,系統才會計算匯總資料。
以下範例是查詢程式碼片段,要求 browser 樞紐維度的總計:
"pivots": [
{
"fieldNames": [
"browser"
],
"limit": 10,
"metricAggregations": [
"TOTAL",
]
},
...
計算指標會在 RunPivotReportResponse 物件的 aggregates 欄位中傳回。如果是匯總指標列,dimensionValues 欄位會包含 RESERVED_TOTAL、RESERVED_MAX 或 RESERVED_MIN 的特殊值。
"aggregates": [
{
"dimensionValues": [
{
"value": "Chrome"
},
{
"value": "RESERVED_TOTAL"
},
{
"value": "RESERVED_TOTAL"
}
],
"metricValues": [
{
"value": "4"
}
]
},
{
"dimensionValues": [
{
"value": "Firefox"
},
{
"value": "RESERVED_TOTAL"
},
{
"value": "RESERVED_TOTAL"
}
],
"metricValues": [
{
"value": "6"
}
]
},
....
}
分頁
與核心報表方法類似,透視要求可讓您在 Pivot 物件中指定 limit 和 offset 欄位,以實作分頁。分頁設定會個別套用至每個資料透視表。
每個 Pivot 物件都必須包含 limit 欄位,才能限制報表基數。
Data API v1 支援多個資料透視,只要每個資料透視的 limit 參數乘積不超過 100,000 即可。
下列程式碼片段示範如何使用 offset 和 limit 欄位,擷取接下來五個 language 維度,偏移量為 10:
{
"fieldNames": [
"language"
],
"offset": 10,
"limit": 5
}
篩選
與核心報表功能類似,如要在透視報表要求中篩選維度,必須使用要求範圍的維度篩選器。
排序
您可以使用 Pivot 物件的 orderBys 欄位 (包含 OrderBy 物件清單),個別控制每個透視圖的透視報表查詢排序行為。
每個 OrderBy 可包含下列其中一項:
- DimensionOrderBy:依維度值排序結果。
- MetricOrderBy:依指標值排序結果。
- PivotOrderBy:用於資料透視查詢,並依據資料透視欄群組中的指標值排序結果。
以下範例顯示資料透視定義的程式碼片段,該定義會依 browser 維度透視報表,並依 sessions 指標遞減排序結果。
{
"fieldNames": [
"browser"
],
"limit": 5,
"orderBys": [
{
"metric": {
"metricName": "sessions"
},
"desc": true
}
]
}
檢舉回覆
透視報表 API 要求的透視報表回應主要包含標頭和資料列。
回應標頭
資料透視報表標頭由 PivotHeaders、DimensionHeaders 和 MetricHeaders 組成,其中列出資料透視報表中的資料欄。
舉例來說,如果報表包含 browser、country 和 language 樞紐維度,以及 sessions 指標,則會產生如下的標頭:
{
"pivotHeaders": [
{
"pivotDimensionHeaders": [
{
"dimensionValues": [
{
"value": "Chrome"
}
]
},
{
"dimensionValues": [
{
"value": "Firefox"
}
]
},
...
],
...
},
{
"pivotDimensionHeaders": [
{
"dimensionValues": [
{
"value": "United States"
}
]
},
{
"dimensionValues": [
{
"value": "Canada"
}
]
},
...
],
...
},
{
"pivotDimensionHeaders": [
{
"dimensionValues": [
{
"value": "English"
}
]
},
{
"dimensionValues": [
{
"value": "French"
}
]
},
...
],
...
}
],
"dimensionHeaders": [
{
"name": "browser"
},
{
"name": "country"
},
{
"name": "language"
}
],
"metricHeaders": [
{
"name": "sessions",
"type": "TYPE_INTEGER"
}
],
...
}
下圖說明 Pivot Report Response 的各個元件在轉譯資料透視報表時扮演的角色:

回覆資料列
runPivotReport 和 batchRunPivotReports 方法的透視報表回應,與 runReport 和 batchRunReports 等核心 Reporting 方法的回應不同,因為每個透視報表回應列代表表格的單一儲存格,而一般報表中的單一回應列代表完整的表格行。
以下範例顯示資料透視報表回應片段,查詢包含 browser、country 和 language 資料透視維度,以及 sessions 指標。資料透視報表的每個儲存格都會個別傳回:
"rows": [
{
"dimensionValues": [
{
"value": "Chrome"
},
{
"value": "United States"
},
{
"value": "English"
}
],
"metricValues": [
{
"value": "1"
}
]
},
{
"dimensionValues": [
{
"value": "Firefox"
},
{
"value": "Canada"
},
{
"value": "French"
}
],
"metricValues": [
{
"value": "3"
}
]
},
...
]
這項資料對應到下表中醒目顯示的兩個儲存格:

用戶端程式庫
下列範例使用用戶端程式庫執行透視查詢,依國家/地區建立工作階段計數報表,並依瀏覽器維度透視。
PHP
use Google\Analytics\Data\V1beta\Client\BetaAnalyticsDataClient; use Google\Analytics\Data\V1beta\DateRange; use Google\Analytics\Data\V1beta\Dimension; use Google\Analytics\Data\V1beta\Metric; use Google\Analytics\Data\V1beta\OrderBy; use Google\Analytics\Data\V1beta\OrderBy\DimensionOrderBy; use Google\Analytics\Data\V1beta\OrderBy\MetricOrderBy; use Google\Analytics\Data\V1beta\Pivot; use Google\Analytics\Data\V1beta\RunPivotReportRequest; use Google\Analytics\Data\V1beta\RunPivotReportResponse; /** * Runs a pivot query to build a report of session counts by country, * pivoted by the browser dimension. * @param string $propertyId Your GA-4 Property ID */ function run_pivot_report(string $propertyId) { // Create an instance of the Google Analytics Data API client library. $client = new BetaAnalyticsDataClient(); // Make an API call. $request = (new RunPivotReportRequest()) ->setProperty('properties/' . $propertyId) ->setDateRanges([new DateRange([ 'start_date' => '2021-01-01', 'end_date' => '2021-01-30', ]), ]) ->setPivots([ new Pivot([ 'field_names' => ['country'], 'limit' => 250, 'order_bys' => [new OrderBy([ 'dimension' => new DimensionOrderBy([ 'dimension_name' => 'country', ]), ])], ]), new Pivot([ 'field_names' => ['browser'], 'offset' => 3, 'limit' => 3, 'order_bys' => [new OrderBy([ 'metric' => new MetricOrderBy([ 'metric_name' => 'sessions', ]), 'desc' => true, ])], ]), ]) ->setMetrics([new Metric(['name' => 'sessions'])]) ->setDimensions([ new Dimension(['name' => 'country']), new Dimension(['name' => 'browser']), ]); $response = $client->runPivotReport($request); printPivotReportResponse($response); } /** * Print results of a runPivotReport call. * @param RunPivotReportResponse $response */ function printPivotReportResponse(RunPivotReportResponse $response) { print 'Report result: ' . PHP_EOL; foreach ($response->getRows() as $row) { printf( '%s %s' . PHP_EOL, $row->getDimensionValues()[0]->getValue(), $row->getMetricValues()[0]->getValue() ); } }
Python
from google.analytics.data_v1beta import BetaAnalyticsDataClient from google.analytics.data_v1beta.types import ( DateRange, Dimension, Metric, OrderBy, Pivot, RunPivotReportRequest, ) def run_sample(): """Runs the sample.""" # TODO(developer): Replace this variable with your Google Analytics 4 # property ID before running the sample. property_id = "YOUR-GA4-PROPERTY-ID" run_pivot_report(property_id) def run_pivot_report(property_id="YOUR-GA4-PROPERTY-ID"): """Runs a pivot query to build a report of session counts by country, pivoted by the browser dimension.""" client = BetaAnalyticsDataClient() request = RunPivotReportRequest( property=f"properties/{property_id}", date_ranges=[DateRange(start_date="2021-01-01", end_date="2021-01-30")], pivots=[ Pivot( field_names=["country"], limit=250, order_bys=[ OrderBy( dimension=OrderBy.DimensionOrderBy(dimension_name="country") ) ], ), Pivot( field_names=["browser"], offset=3, limit=3, order_bys=[ OrderBy( metric=OrderBy.MetricOrderBy(metric_name="sessions"), desc=True ) ], ), ], metrics=[Metric(name="sessions")], dimensions=[Dimension(name="country"), Dimension(name="browser")], ) response = client.run_pivot_report(request) print_run_pivot_report_response(response) def print_run_pivot_report_response(response): """Prints results of a runPivotReport call.""" print("Report result:") for row in response.rows: for dimension_value in row.dimension_values: print(dimension_value.value) for metric_value in row.metric_values: print(metric_value.value)
Node.js
// TODO(developer): Uncomment this variable and replace with your // Google Analytics 4 property ID before running the sample. // propertyId = 'YOUR-GA4-PROPERTY-ID'; // Imports the Google Analytics Data API client library. const {BetaAnalyticsDataClient} = require('@google-analytics/data'); // Initialize client that will be used to send requests. This client only // needs to be created once, and can be reused for multiple requests. const analyticsDataClient = new BetaAnalyticsDataClient(); // Runs a pivot query to build a report of session counts by country, pivoted // by the browser dimension. async function runPivotReport() { const [response] = await analyticsDataClient.runPivotReport({ property: `properties/${propertyId}`, dateRanges: [ { startDate: '2021-01-01', endDate: '2021-01-30', }, ], pivots: [ { fieldNames: ['country'], limit: 250, orderBys: [ { dimension: { dimensionName: 'country', }, }, ], }, { fieldNames: ['browser'], offset: 3, limit: 3, orderBys: [ { metric: { metricName: 'sessions', }, desc: true, }, ], }, ], metrics: [ { name: 'sessions', }, ], dimensions: [ { name: 'country', }, { name: 'browser', }, ], }); printPivotReportResponse(response); } runPivotReport(); // Prints results of a runReport call. function printPivotReportResponse(response) { console.log('Report result:'); response.rows.forEach((row) => { row.dimensionValues.forEach((dimensionValue) => { console.log(dimensionValue.value); }); row.metricValues.forEach((metricValue) => { console.log(metricValue.value); }); }); }
試用版應用程式
如需使用 JavaScript 建構及顯示透視報表的範例,請參閱 Google Analytics API v1 透視報表示範應用程式。