在Bigquery中获取下一个值作为当前值

时间:2019-05-15 17:10:49

标签: sql google-bigquery

我有这样的数据

Row order_id    date_order  partner_id  
1   SNB1905/0007786 2019-05-15 10:17:57 UTC 70959
2   SNB1905/0007786 2019-05-15 10:17:56 UTC 70959
3   SNB1904/0008810 2019-04-30 07:18:11 UTC 70959
4   SNB1902/0003122 2019-02-20 07:05:00 UTC 70959

我想获取先前的order_id,并将date_order转换为我的时区。所以我已经完成了这样的查询

SELECT
  order_id,
  DATE(date_order,"Asia/Jakarta") AS date_only,
  partner_id,
  LAG(origin,1) OVER(PARTITION BY partner_id order by date_order) prev_order
FROM
  `my_table`
WHERE
  partner_id = 70959
ORDER BY
  date_order DESC

我得到的结果是这样的

Row order_id    date_only   partner_id  prev_order  
1   SNB1905/0007786 2019-05-15 70959 SNB1904/0008810
2   SNB1905/0007786 2019-05-15 70959 SNB1905/0007786
3   SNB1904/0008810 2019-04-30 70959 SNB1902/0003122
4   SNB1902/0003122 2019-02-20 70959 null

我想要的结果是这样的

Row order_id  date_only partner_id  prev_order  
1   SNB1905/0007786 2019-05-15 70959 SNB1904/0008810
2   SNB1905/0007786 2019-05-15 70959 SNB1904/0008810
3   SNB1904/0008810 2019-04-30 70959 SNB1902/0003122
4   SNB1902/0003122 2019-02-20 70959 null

如果order_id等于prev_order,我想在prev_order列中获取上一个值。

请帮助我解决此问题。谢谢你。

1 个答案:

答案 0 :(得分:1)

以下是用于BigQuery标准SQL

#standardSQL
SELECT
  order_id,
  date_only,
  partner_id,  
  ( SELECT order_id FROM UNNEST(prev_orders) prev_order
    WHERE t.order_id != order_id
    ORDER BY date_order DESC LIMIT 1
  ) prev_order
FROM (
  SELECT
    order_id,
    date_order,
    DATE(date_order,"Asia/Jakarta") AS date_only,
    partner_id,
    ARRAY_AGG(STRUCT(order_id AS order_id, date_order AS date_order)) 
      OVER(PARTITION BY partner_id ORDER BY date_order ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING) prev_orders
  FROM `project.dataset.table`
) t
WHERE partner_id = 70959
-- ORDER BY date_order DESC

如果要应用于您的问题的样本数据-结果为

Row order_id        date_only   partner_id  prev_order   
1   SNB1905/0007786 2019-05-15  70959       SNB1904/0008810  
2   SNB1905/0007786 2019-05-15  70959       SNB1904/0008810  
3   SNB1904/0008810 2019-04-30  70959       SNB1902/0003122  
4   SNB1902/0003122 2019-02-20  70959       null