首页 > 解决方案 > 使用条件滞后语句查询

问题描述

我正在尝试查找该行满足某些条件的列的先前值。考虑下表:

| 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 。

我怀疑它可以使用窗口函数的组合来完成,但我就是想不通。

标签: google-bigquerybigquery-standard-sql

解决方案


我将 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

推荐阅读