sql—获取下一个带时间戳的结果以绑定到上一个结果

mdfafbf1  于 2021-07-24  发布在  Java
关注(0)|答案(2)|浏览(337)

我的表在bigquery中看起来像这样

+--------------------+------------+--------+--------+
|     TimeStamp      |  Session   |  Type  | Result |
+--------------------+------------+--------+--------+
| 7/28/2020 16:05:02 | 1595952288 | Select |  53402 |
| 7/28/2020 16:05:16 | 1595952288 | Menu   |      2 |
| 7/28/2020 16:05:25 | 1595952288 | Select |  53405 |
| 7/28/2020 16:05:36 | 1595952288 | Menu   |      1 |
+--------------------+------------+--------+--------+

我想能够拉数据如下所示

+--------------------+------------+--------+--------+---------+
|     TimeStamp      |  Session   |  Type  | Result | Confirm |
+--------------------+------------+--------+--------+---------+
| 7/28/2020 16:05:02 | 1595952288 | Select |  53402 |       2 |
| 7/28/2020 16:05:25 | 1595952288 | Select |  53405 |       1 |
+--------------------+------------+--------+--------+---------+

基本上,数据是一个人在一个应用程序的一个会话中,他们输入一个5位数的数字,然后要求他们确认。
五位数字将位于type=select下面
1或2将在type=菜单下,1表示已确认,2表示错误,他们希望重新输入5位数字
我试着把下一行和基于下一个时间戳的5位数字联系起来,并把它放到同一行去报告它。
这是我创建的sql,我认为它不正确,因为它会产生重复。我认为有更好的方法,但效率不高。事实上,这可能是完全错误的。

Select DISTINCT 
table1.Session, 
table1.Result, 
subtable1.Confirm

FROM 
`googleBQ_table` as table1
Left Join (
Select 
Result as Confirm,
Session,
MAX(TimeStamp)

FROM 
`googleBQ_table` 

WHERE Type =  'Menu' and LENGTH(Result) < 2

group by 1,2) as sub_table1 on sub_table1.Session = table1.Session

WHERE
table1.Session = '1595952288' and LENGTH(table1.Result) = 5

先谢谢你。

ux6nzvsh

ux6nzvsh1#

下面是bigquery标准sql
在应用程序的会话中,他们输入一个5位数字,然后要求他们确认。
基于上面的-我假设确认行总是在select行之后-下面就是这样做的


# standardSQL

SELECT * FROM (
  SELECT *, LEAD(result) OVER(confirmation) Confirm 
  FROM `project.dataset.table`
  WINDOW confirmation AS (PARTITION BY session ORDER BY TimeStamp)
) 
WHERE type = 'Select'

如果应用于问题的样本数据-结果是

Row TimeStamp           Session     Type    Result  Confirm  
1   7/28/2020 16:05:02  1595952288  Select  53402   2    
2   7/28/2020 16:05:25  1595952288  Select  53405   1
kt06eoxx

kt06eoxx2#

假设“select”和“menu”行正确交错,则可以使用窗口函数:

select timestamp, session, type, result, lead_result confirm
from (
    select 
        t.*, 
        lead(case when type = 'Menu' then result end) 
            over(partition by session order by timestamp) lead_result
    from `googleBQ_table` t
) t
where type = 'Select'

相关问题