计算Google BigQuery中的月差异

时间:2015-01-10 20:06:33

标签: google-bigquery

BigQuery不允许您在DATEDIFF中选择时段MONTH。

在BigQuery中有没有其他方法可以做到这一点。

我可以使用以下但不是几个月来获得天差。

SELECT 
  OrderID,
  OrderDate,
  STRING( YEAR ( OrderDate )) + '-' + STRING(MONTH ( OrderDate )) as order_month, 
  UserID,
  FirstOrderDate
DATEDIFF( OrderDate, FirstOrderDate) as date_diff,
FROM [orders.orders] 
WHERE FirstOrderDate > DATE_ADD(CURRENT_TIMESTAMP(), -1, 'YEAR')

2 个答案:

答案 0 :(得分:4)

这个怎么样?

(12 * YEAR(t2) + MONTH(t2)) - (12 * YEAR(t1) + MONTH(t1))
    + IF (DAY(t2) >= DAY(t1), 0, -1)

运行几个例子,它看起来像你想要的那样:

SELECT 
(12 * YEAR(t2) + MONTH(t2)) - (12 * YEAR(t1) + MONTH(t1))
    + IF (DAY(t2) >= DAY(t1), 0, -1)
FROM 
    (SELECT TIMESTAMP("2010-12-01") as t1, TIMESTAMP("2011-01-01") as t2), // 1
    (SELECT TIMESTAMP("2010-12-02") as t1, TIMESTAMP("2011-01-01") as t2), // 0
    (SELECT TIMESTAMP("2010-12-01") as t1, TIMESTAMP("2011-12-01") as t2), // 12
    (SELECT TIMESTAMP("2010-10-21") as t1, TIMESTAMP("2015-01-10") as t2)  // 50

答案 1 :(得分:0)

使用标准SQL,您可以使用date_diff

#StandardSQL
select date_diff(current_date, date '2018-03-06', month)