如何在Google BigQuery中进行汇总和分组

时间:2019-03-07 21:53:17

标签: sql google-bigquery

在Google BigQuery中,我想根据某些维度(在这种情况下,按广告系列和合作伙伴)汇总指标。当我使用下面的代码时,出现错误:

GROUP BY列表中不存在表达式'a.genre'。

有人可以告诉我我需要在脚本中修复的内容吗?谢谢!
请参见下面的示例表(忽略下表中的标题与提供的脚本完全不匹配):

enter image description here

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)

1 个答案:

答案 0 :(得分:2)

在SQL中,通常,如果要使用组进行聚合,则必须确定select语句中的字段是聚合还是组。您不能没有任何上下文就让它站在那里。因此,在您的情况下,您可能要删除所有其他字段

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)

或将它们添加为您要汇总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)