google-bigquery - 使用条件滞后语句查询
问题描述
我正在尝试查找该行满足某些条件的列的先前值。考虑下表:
| user_id | session_id | time | referrer |
|---------|------------|------------|------------|
| 1 | 1 | 2018-01-01 | [NULL] |
| 1 | 2 | 2018-02-01 | google.com |
| 1 | 3 | 2018-03-01 | google.com |
我想为每个会话查找引用者为 NULL 的 session_id 的前一个值。因此,对于第二行和第三行, 的值parent_session_id
应该是 1。
但是,仅使用lag(session_id) over (partition by user_id order by time)
,我将parent_session_id
在第三行得到 =2 。
我怀疑它可以使用窗口函数的组合来完成,但我就是想不通。
解决方案
我将 last_value() 与 if() 结合使用:
WITH t AS (SELECT * FROM UNNEST([
struct<user_id int64, session_id int64, time date, referrer string>(1, 1, date('2018-01-01'), NULL),
(1,2,date('2018-02-01'), 'google.com'),
(1,3,date('2018-03-01'), 'google.com')
]) )
SELECT
*,
last_value(IF(referrer is null, session_id, NULL) ignore nulls)
over (partition by user_id order by time rows between unbounded preceding and 1 preceding) lastNullrefSession
FROM t
推荐阅读
- java - 在@Recover 方法上使用@Transaction 时出现异常
- android - 在矢量图像上显示标记以构建自定义室内地图 Android
- android - windowSplashScreenAnimatableIcon not found
- amazon-web-services - 如何使用 Terraform 自动切换到 AWS 的 RDS 中的新参数组?
- mongodb - 如何使用 Apache Camel 从两个集合中获取请求的数据
- selenium - Maven 项目 - 我们在编写自动化脚本时是否需要设置属性?
- sql - DBMS 驱动程序异常是:没有更多数据可以从套接字读取
- flutter - 如何在没有屏幕闪烁的情况下将加载微调器添加到布局生成器?
- python - Saltstack在python脚本中从master向minions发送事件
- python - 如何在 Python 中使用这些列表获得以下输出?