如何根据事件在BigQuery中创建通道路径?

时间:2017-04-14 08:42:21

标签: google-analytics google-bigquery

我想在用户级别在Bigquery中创建频道路径。我希望路径在事务发生时结束。然后下一次访问将开始一条新路径。目前,每个用户有一条路径汇总所有交易。请参阅下面提供的代码。我还包括当前的OUTPUT TABLE和所需的OUTPUT TABLE。

我的想法是创建一个计算交易的新列。此值将从0开始,并且需要在事务发生后递增1。然后我将此值与user_id值合并,并对该变量上的聚合字符串进行分组。但我不知道该怎么做。

提前致谢!

#standardSQL
WITH yourTable AS (
  SELECT 1 AS user_id,'1a' as visit_id, '2017-01-01 14:10:12' AS DATETIME, 
'google cpc' AS channelgrouping, 0 AS transaction , 1 as visit UNION ALL
  SELECT 1, '1b', '2017-01-01 20:10:12', 'email', 1, 1 UNION ALL
  SELECT 1, '1c','2017-01-03 08:10:12', 'direct', 0, 1 UNION ALL
  SELECT 1, '1d','2017-01-04 13:10:14', 'organic', 1, 1
)
SELECT 
  user_id, 
  STRING_AGG(channelgrouping, ' > ' ORDER BY DATETIME) AS channelgrouping_path,
  SUM(transaction) AS transaction,
  SUM(visit) AS visits
 FROM yourTable
GROUP BY user_id

输出表

user_id|channgelgrouping_path                |Transactions|Visits
1      |google cpc > email > direct > organic| 2          | 4

期望的输出表

user_id|channgelgrouping_path                |Transactions|Visits
1      |google cpc > email                   | 1          | 2
1      |direct > organic                     | 1          | 2

1 个答案:

答案 0 :(得分:2)

尝试以下

  
#standardSQL
WITH yourTable AS (
  SELECT 1 AS user_id,'1a' AS visit_id, '2017-01-01 14:10:12' AS DATETIME, 
'google cpc' AS channelgrouping, 0 AS transaction , 1 AS visit UNION ALL
  SELECT 1, '1b', '2017-01-01 20:10:12', 'email', 1, 1 UNION ALL
  SELECT 1, '1c','2017-01-03 08:10:12', 'direct', 0, 1 UNION ALL
  SELECT 1, '1d','2017-01-04 13:10:14', 'organic', 1, 1
)
SELECT
  user_id, 
  STRING_AGG(channelgrouping, ' > ' ORDER BY DATETIME) AS channelgrouping_path,
  SUM(transaction) AS transaction,
  SUM(visit) AS visits
FROM (
  SELECT 
    *, 
    SUM(transaction) OVER(PARTITION BY user_id ORDER BY datetime 
                ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING
    ) AS grp
  FROM yourTable
)
GROUP BY user_id, IFNULL(grp, 0)