如何获得(多个)两个不同行之间的差异?

时间:2019-05-21 05:08:11

标签: google-bigquery

我有一组包含某些字段的数据:monthcustomer_idrow_num(排名)和verified_date

等级字段指示每个客户的第一次(1)和第二次(2)购买。我想知道每个客户第一次购买和第二次购买之间的时差,并且仅显示its first month = 1,其中row_num = 1。

https://i.ibb.co/PjJk5Y0/Capture.png

所以我的预期结果如下图所示:

https://i.ibb.co/y5Mww7k/Capture-2.png

我在StandardSQL中使用Google Bigquery

row_num, verified_date
  from table
  GROUP BY 1, 2```

1 个答案:

答案 0 :(得分:0)

我们可以在此处尝试使用数据透视查询,并按customer_id进行汇总:

SELECT
    MAX(CASE WHEN row_num = 1 THEN month END) AS month,
    customer_id,
    1 AS row_num,
    DATE_DIFF(MAX(CASE WHEN row_num = 2 THEN verified_date END),
              MAX(CASE WHEN row_num = 1 THEN verified_date END), DAY) AS difference
FROM yourTable
GROUP BY
    customer_id;