【问题标题】:Summing totals from nested and unnested data in a single query在单个查询中汇总嵌套和非嵌套数据的总计
【发布时间】:2018-06-15 11:57:04
【问题描述】:

我正在处理嵌套的 Google Analytics 数据以构建查询,我需要取消嵌套 3 个级别才能获得我需要的所有字段,但是一旦我取消嵌套我的 .totals 字段的 SUM() 就太远了高,我猜是因为它们的值被重复了。

我无法在命中级别上识别弹跳,因此我需要使用totals.bounces 来获取此值。

如何调整下面的查询以获得正确的跳出和收入总和以及未嵌套值的总数?

SELECT
  customDimension.value AS UserID,
  # Visits from this individual
  SUM(totals.visits) AS visits,
  # Orders from this individual
  COUNT(DISTINCT hits.transaction.transactionId) AS orders,
  # AOV
  SAFE_DIVIDE(SUM(hits.transaction.transactionRevenue)/1000000 , COUNT(DISTINCT hits.transaction.transactionId)) AS AOV,
  #Bounces from this individual
   IFNULL(SUM(totals.bounces),
    0) AS bounces,
  IFNULL(SUM(hits.transaction.transactionRevenue)/1000000,
    0) AS revenue,
  # Conversion rate of the individual
  SAFE_DIVIDE(COUNT(DISTINCT hits.transaction.transactionId),COUNT(DISTINCT CONCAT(CAST(fullVisitorId AS STRING),CAST(visitId AS STRING)))) AS conversion_rate,

  ROUND(IFNULL(SUM(totals.bounces)/COUNT(DISTINCT CONCAT(CAST(fullVisitorId AS STRING),CAST(visitId AS STRING))),
      0),5) AS bounce_rate,

FROM
  `MY.DATA.ga_sessions_20*` AS t
CROSS JOIN
  UNNEST (hits) AS hits
CROSS JOIN
  UNNEST(t.customdimensions) AS customDimension
CROSS JOIN
  UNNEST(hits.product) AS hits_product

  WHERE parse_date('%y%m%d', _table_suffix) between 
DATE_sub(current_date(), interval 7 day) and
DATE_sub(current_date(), interval 1 day)

  AND customDimension.index = 2
  AND customDimension.value NOT LIKE "true"
  AND customDimension.value NOT LIKE "false"
  AND customDimension.value NOT LIKE "undefined"
  AND customDimension.value IS NOT NULL
GROUP BY
  UserID,
  hits.eventInfo.eventCategory

【问题讨论】:

  • 1) 您没有使用 hits_product,因此您可能需要删除相应的 UNNEST 2) 如果您想要正确的反弹总和 - 您需要想出一些将它们分布在 hits.eventInfo 中的逻辑。 eventCategory 和 customDimension.value
  • 以前帖子中的解决方案存在类似问题,可能会有所帮助。 stackoverflow.com/questions/43880721stackoverflow.com/questions/45231791

标签: sql google-bigquery


【解决方案1】:

现在我对 BigQuery 有了更多的经验,我可以根据我今天的实现方式来回答这个问题。

使用WITH(),我创建了多个查询并包含到我需要在这些级别的字段中,例如,我的第一个WITH() 语句将没有取消嵌套,并且将正确地对totals. 字段求和。第二个WITH() 可以然后UNNEST() 匹配级别并在此处汇总我要计算的字段。

这些查询然后可以与一个公共连接联合起来,并在取消嵌套的每个级别显示正确的值,而不会重复。

【讨论】:

    猜你喜欢
    • 2015-10-17
    • 2016-04-20
    • 2015-12-15
    • 2013-10-11
    • 1970-01-01
    • 1970-01-01
    • 2020-11-05
    • 1970-01-01
    • 2019-09-18
    相关资源
    最近更新 更多