如何在BigQuery中执行熊猫列移动?

时间:2018-08-03 09:05:00

标签: google-bigquery

假设我们有一个包含以下数据的数据集:

timestamp,col1

1533286270,1
1533286271,2
1533286272,3
1533286273,4
1533286274,5

我想获取col1col1_prev之前的值,以便能够进行比较。结果应与pandas.shift(-1)相同。

如何通过普通的SQL查询实现此功能?

查询结果应如下所示:

timestamp,col1,col1_prev

1533286270,1,NULL
1533286271,2,1
1533286272,3,2
1533286273,4,3
1533286274,5,4

1 个答案:

答案 0 :(得分:4)

使用lag()函数是一种方法:

WITH
  input AS (
  SELECT
    1533286270 AS timestamp,
    1 AS col1
  UNION ALL
  SELECT
    1533286271 AS timestamp,
    2 AS col1
  UNION ALL
  SELECT
    1533286272 AS timestamp,
    3 AS col1
  UNION ALL
  SELECT
    1533286273 AS timestamp,
    4 AS col1
  UNION ALL
  SELECT
    1533286274 AS timestamp,
    5 AS col1 )
SELECT
  timestamp,
  col1,
  LAG(col1) OVER(ORDER BY col1) AS col1_prev
FROM
  input

enter image description here