Google bigquery BigQuery-如果客户ID匹配,则与前一行的时间差

Google bigquery BigQuery-如果客户ID匹配,则与前一行的时间差,google-bigquery,timedelta,Google Bigquery,Timedelta,我有一张大致如下的订单表 consumerID || TransactionDate || Revenue 1 || 2015-01-01 || 55 1 || 2015-02-01 || 65 2 || 2015-01-01 || 10 3 || 2015-03-01 || 20 4 || 2015-01-01 || 25 4 || 20

我有一张大致如下的订单表

consumerID || TransactionDate || Revenue
1          || 2015-01-01      || 55
1          || 2015-02-01      || 65
2          || 2015-01-01      || 10
3          || 2015-03-01      || 20
4          || 2015-01-01      || 25
4          || 2015-01-01      || 45
4          || 2015-03-01      || 55
我想添加一个列,计算出客户下一个订单所用的时间(以月为单位),以便数据如下所示

consumerID || TransactionDate || Revenue || OrderCount || TimeInMonths
1          || 2015-01-01      || 55      || 1          || null
1          || 2015-02-01      || 65      || 2          || 1
2          || 2015-01-01      || 10      || 1          || null
3          || 2015-03-01      || 20      || 1          || null
4          || 2015-01-01      || 25      || 1          || null
4          || 2015-01-01      || 45      || 2          || 0
4          || 2015-03-01      || 55      || 3          || 2
我已经了解了如何使用以下公式计算客户订单的运行计数

ROW_NUMBER() OVER (PARTITION BY o.ConsumerID ORDER BY TransactionDate ASC) OrderNumber,
我想做一些类似的事情,但如果计算出月份的差异,我就被难倒了

我想要的是

如果是第一个订单,或者是看到客户的最早日期,则为空。 如果订单号2计算与第一个订单的差异,如果第三个订单计算与第二个订单的差异,以此类推

如果方便的话,我可以确保数据按consumerId和事务日期排序

SELECT ConsumerID, TransactionDate, Revenue, OrderCount,
  DATEDIFF(TransactionDate, prevTransactionDate) AS TimeInDays,
  INTEGER(DATEDIFF(TransactionDate, prevTransactionDate)/30) AS TimeInMonths
FROM (
  SELECT ConsumerID, TransactionDate, Revenue, 
    ROW_NUMBER() OVER(PARTITION BY ConsumerID 
        ORDER BY TransactionDate ASC) OrderCount,
    LAG(TransactionDate) OVER(PARTITION BY ConsumerID 
        ORDER BY TransactionDate ASC) prevTransactionDate
  FROM YourTable 
) ORDER BY ConsumerID, TransactionDate 

以天计算是显而易见的。以月计算要求您设置如何以天为单位从差异计算的业务逻辑。以上是应用的示例规则。

哦,天哪,对不起,我以为我已经。我很抱歉