简体   繁体   English

[SQL][Bigquery] Case 何时将前一行作为条件

[英][SQL][Bigquery] Case When to take preceding row for a condition

So for a table like this i want to have another column which has the reqd_col value if cond_value is > 100 and to take the previous value in other cases.因此,对于这样的表,如果 cond_value > 100,我希望有另一列具有 reqd_col 值,并在其他情况下采用先前的值。

User用户 cond_Value条件值 Reqd_Col Reqd_Col
123456 123456 159 159 12:30 12:30
123456 123456 34 34 12:32 12:32
123456 123456 46 46 12:35 12:35
123456 123456 98 98 12:37 12:37
123456 123456 123 123 12:56 12:56
123456 123456 12 12 13:00 13:00
789000 789000 100 100 16:00 16:00
789000 789000 54 54 16:10 16:10
789000 789000 23 23 16:14 16:14
789000 789000 122 122 17:05 17:05
789000 789000 98 98 17:08 17:08
789000 789000 133 133 17:23 17:23

So the output should look like所以 output 应该是这样的

User用户 cond_Value条件值 Reqd_Col Reqd_Col Output Output
123456 123456 159 159 12:30 12:30 12:30 12:30
123456 123456 34 34 12:32 12:32 12:30 12:30
123456 123456 46 46 12:35 12:35 12:30 12:30
123456 123456 98 98 12:37 12:37 12:30 12:30
123456 123456 123 123 12:56 12:56 12:56 12:56
123456 123456 12 12 13:00 13:00 12:56 12:56
789000 789000 100 100 16:00 16:00 16:00 16:00
789000 789000 54 54 16:10 16:10 16:00 16:00
789000 789000 23 23 16:14 16:14 16:00 16:00
789000 789000 122 122 17:05 17:05 17:05 17:05
789000 789000 98 98 17:08 17:08 17:05 17:05
789000 789000 133 133 17:23 17:23 17:23 17:23

Ideally i would like to have this as a view in BigQuery.理想情况下,我希望将其作为 BigQuery 中的视图。

Try below query.试试下面的查询。

SELECT *, LAST_VALUE(IF(cond_Value >= 100, Reqd_Col, NULL) IGNORE NULLS) OVER w AS Output
  FROM sample_table
WINDOW w AS (PARTITION BY User ORDER BY PARSE_TIME('%R', Reqd_Col))
 ORDER BY 1, 3;

+--------+------------+----------+--------+
|  User  | cond_Value | Reqd_Col | Output |
+--------+------------+----------+--------+
| 123456 |        159 | 12:30    | 12:30  |
| 123456 |         34 | 12:32    | 12:30  |
| 123456 |         46 | 12:35    | 12:30  |
| 123456 |         98 | 12:37    | 12:30  |
| 123456 |        123 | 12:56    | 12:56  |
| 123456 |         12 | 13:00    | 12:56  |
| 789000 |        100 | 16:00    | 16:00  |
| 789000 |         54 | 16:10    | 16:00  |
| 789000 |         23 | 16:14    | 16:00  |
| 789000 |        122 | 17:05    | 17:05  |
| 789000 |         98 | 17:08    | 17:05  |
| 789000 |        133 | 17:23    | 17:23  |
+--------+------------+----------+--------+

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM