简体   繁体   中英

How to Aggregate and Group By in Google BigQuery

In Google BigQuery, I'd like to roll up metrics based on certain dimensions (in this case, by campaign and partner). When I use the code below, I'm getting the error:

Expression 'a.genre' is not present in the GROUP BY list.

Can someone please advise what I need to fix in my script? Thank you!
Please see below for sample table (disregard how the headers in the table below don't exactly match the provided script):

在此处输入图片说明

SELECT
  SUM(a.amount) totalcost, 
  a.campaign_name, 
  c.friendly_campaign, 
  p.friendly_partner_name, 
  a.partner_name, 
  a.genre, 
  a.season, 
  a.package
FROM
  [TABLE 1] a
  LEFT OUTER JOIN
  [TABLE 2] p
ON
  a.partner_name = p.raw_partner_name
LEFT OUTER JOIN
  [TABLE 3] c 
ON
  a.campaign_name = c.campaign
GROUP BY ROLLUP(c.friendly_campaign, p.friendly_partner_name)

In SQL, in general, - if you're aggregating using groups - you have to decide whether a field in your select statement gets aggregated or is a group. You can't just let it stand there without any context. So in your case you probably want to either remove all other fields

SELECT
  SUM(a.amount) totalcost, 
  c.friendly_campaign, 
  p.friendly_partner_name, 
FROM
  [TABLE 1] a
  LEFT OUTER JOIN
  [TABLE 2] p
ON
  a.partner_name = p.raw_partner_name
LEFT OUTER JOIN
  [TABLE 3] c 
ON
  a.campaign_name = c.campaign
GROUP BY ROLLUP(c.friendly_campaign, p.friendly_partner_name)

or add them as groups in which you're aggregating a.amount :

SELECT
  SUM(a.amount) totalcost, 
  a.campaign_name, 
  c.friendly_campaign, 
  p.friendly_partner_name, 
  a.partner_name, 
  a.genre, 
  a.season, 
  a.package
FROM
  [TABLE 1] a
  LEFT OUTER JOIN
  [TABLE 2] p
ON
  a.partner_name = p.raw_partner_name
LEFT OUTER JOIN
  [TABLE 3] c 
ON
  a.campaign_name = c.campaign
GROUP BY ROLLUP(2,3,4,5,6,7,8)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM