gpt4 book ai didi

sql - 如何计算 SQL Bigquery 中另一个事件之前特定事件的数量?

转载 作者:行者123 更新时间:2023-12-02 00:37:30 26 4
gpt4 key购买 nike

我有一个包含日期、事件和用户的表。有一个名为“A”的事件。我想知道在 Sql Bigquery 中事件“A”之前和之后特定事件发生了多少次。例如,

   User           Date             Events
123 2018-02-13 X.Y.A
123 2018-02-12 X.Y.B
134 2018-02-10 Y.Z.A
123 2018-02-11 A
123 2018-02-01 X.Y.Z
134 2018-02-05 X.Y.B
134 2018-02-04 A

输出是这样的

User       Event    Before   After
123 A 1 3
134 A 0 1

我必须计算的事件包含一个特定的前缀。意味着我必须检查以(X.Y.然后是某个事件名称)开头的事件。因此,X.Y.SomeEvent 是我必须为其设置计数器的事件。有什么建议吗?

最佳答案

下面是 BigQuery SQL

#standardSQL
SELECT user, event, before, after
FROM (
SELECT user, event,
COUNTIF(event LIKE 'X.Y.%') OVER(PARTITION BY user ORDER BY dt ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING) before,
COUNTIF(event LIKE 'X.Y.%') OVER(PARTITION BY user ORDER BY dt ROWS BETWEEN 1 FOLLOWING AND UNBOUNDED FOLLOWING ) after
FROM `project.dataset.events`
)
WHERE event = 'A'
-- ORDER BY user

你可以在你的问题中用虚拟数据来测试它

#standardSQL
WITH `project.dataset.events` AS (
SELECT 123 user, '2018-02-13' dt, 'X.Y.A' event UNION ALL
SELECT 123, '2018-02-12', 'X.Y.B' UNION ALL
SELECT 123, '2018-02-11', 'A' UNION ALL
SELECT 134, '2018-02-10', 'Y.Z.A' UNION ALL
SELECT 134, '2018-02-05', 'X.Y.B' UNION ALL
SELECT 134, '2018-02-04', 'A' UNION ALL
SELECT 123, '2018-02-01', 'X.Y.Z'
)
SELECT user, event, before, after
FROM (
SELECT user, event,
COUNTIF(event LIKE 'X.Y.%') OVER(PARTITION BY user ORDER BY dt ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING) before,
COUNTIF(event LIKE 'X.Y.%') OVER(PARTITION BY user ORDER BY dt ROWS BETWEEN 1 FOLLOWING AND UNBOUNDED FOLLOWING ) after
FROM `project.dataset.events`
)
WHERE event = 'A'
ORDER BY user

关于sql - 如何计算 SQL Bigquery 中另一个事件之前特定事件的数量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48794727/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com