如何通过Google Analytics Reporting API获取指定source medium的会话数据汇总值?
How to Aggregate Session Data for Multiple Source/Medium Values in Google Analytics Reporting API
Absolutely! You can tweak your Google Analytics Reporting API request to get the aggregated session count for both google / cpc and facebook / cpc combined. Here are a couple of simple, effective approaches:
Approach 1: Get Only the Aggregated Total
If you just need the combined session count (and don't need to see individual breakdowns for each source/medium), remove the ga:sourceMedium dimension and adjust your filter logic to match either value:
{ "reportRequests": [ { "viewId": "XXXXXX", "dateRanges": [ { "startDate": "2021-07-01", "endDate": "2021-07-31" }, { "startDate": "2020-07-01", "endDate": "2020-07-31" } ], "metrics": [ { "expression": "ga:sessions" } ], "dimensionFilterClauses": [ { "operator": "OR", // Ensures either filter match is included "filters": [ { "dimensionName": "ga:sourceMedium", "operator": "EXACT", "expressions": ["google / cpc"] }, { "dimensionName": "ga:sourceMedium", "operator": "EXACT", "expressions": ["facebook / cpc"] } ] } ] } ] }
Key Changes:
- Removed the
ga:sourceMediumdimension: Without this dimension, the API returns a single aggregated value for all matching rows. - Added
"operator": "OR"to the filter clause: This fixes your original request's implicitANDlogic (which would return no results, since a row can't belong to two source/mediums at once).
You can simplify the filter even further using the IN operator instead of two separate filters:
"dimensionFilterClauses": [ { "filters": [ { "dimensionName": "ga:sourceMedium", "operator": "IN", "expressions": ["google / cpc", "facebook / cpc"] } ] } ]
Approach 2: Get Individual Breakdowns + Aggregated Total
If you want to see both the individual session counts for each source/medium and their combined total, keep the ga:sourceMedium dimension and enable row totals:
{ "reportRequests": [ { "viewId": "XXXXXX", "dateRanges": [ { "startDate": "2021-07-01", "endDate": "2021-07-31" }, { "startDate": "2020-07-01", "endDate": "2020-07-31" } ], "metrics": [ { "expression": "ga:sessions" } ], "dimensions": [ { "name": "ga:sourceMedium" } ], "dimensionFilterClauses": [ { "operator": "OR", "filters": [ { "dimensionName": "ga:sourceMedium", "operator": "EXACT", "expressions": ["google / cpc"] }, { "dimensionName": "ga:sourceMedium", "operator": "EXACT", "expressions": ["facebook / cpc"] } ] } ], "showRowTotals": true // Adds a total row with combined session counts } ] }
What This Does:
- Returns two rows with individual session counts for
google / cpcandfacebook / cpc - Adds an additional "Total" row at the end with the aggregated sum of both values for each date range
内容的提问来源于stack exchange,提问作者Anders




