2017-07-17 34 views
1

是否可以在BigQuery中以某種方式使用LAG(),直到它滿足特定值或條件?換句話說,我需要offset根據要跳轉的行數來動態變化。LAG(偏移量)直到BigQuery中的值達到

例如:

#standardSQL 
WITH input AS (
    SELECT 1 AS id, 1 AS col_1, 'A' AS col_2 UNION ALL 
    SELECT 2 AS id, 0 AS col_1, 'B' AS col_2 UNION ALL 
    SELECT 3 AS id, 0 AS col_1, 'C' AS col_2 UNION ALL 
    SELECT 4 AS id, 1 AS col_1, 'D' AS col_2 UNION ALL 
    SELECT 5 AS id, 1 AS col_1, 'E' AS col_2 UNION ALL 
    SELECT 6 AS id, 0 AS col_1, 'F' AS col_2 UNION ALL 
    SELECT 7 AS id, 1 AS col_1, 'G' AS col_2) 

如果col_1等於0,然後採取的col_2的值,其中前述col_1最後等於1

希望的輸出:

enter image description here

我可以通過自我加入來完成但如果可能的話,我寧願避免使用連接,即必須有更聰明的方法!

回答

1

的BigQuery標準SQL

#standardSQL 
WITH input AS (
    SELECT 1 AS id, 1 AS col_1, 'A' AS col_2 UNION ALL 
    SELECT 2 AS id, 0 AS col_1, 'B' AS col_2 UNION ALL 
    SELECT 3 AS id, 0 AS col_1, 'C' AS col_2 UNION ALL 
    SELECT 4 AS id, 1 AS col_1, 'D' AS col_2 UNION ALL 
    SELECT 5 AS id, 1 AS col_1, 'E' AS col_2 UNION ALL 
    SELECT 6 AS id, 0 AS col_1, 'F' AS col_2 UNION ALL 
    SELECT 7 AS id, 1 AS col_1, 'G' AS col_2 
) 
SELECT id, col_1, col_2, 
    IF(col_1 = 0, FIRST_VALUE(col_2) OVER(PARTITION BY grp ORDER BY col_1 DESC), NULL) AS col_3 
FROM (
    SELECT * , 
    SUM(col_1) OVER(ORDER BY id) AS grp 
    FROM input 
) 
-- ORDER BY id 
+0

徹底無緣在文檔的'FIRST_VALUE'功能。謝謝米哈伊爾! –