简体   繁体   English

使用Bigquery,如何使用涉及日期的条件语句

[英]Using Bigquery , how to use conditional statement involving dates

I require a column which counts the number days ie(Order Date - 01Jan2020).我需要一个计算天数的列,即(订单日期 - 2020 年 1 月 1 日)。

Condition is -> if Order Date lies between 01Jan2020 and 31Mar2020 then (DATE_DIFF('2020-01-31',Order Date, DAY)) else 0条件是-> 如果订单日期介于 2020 年 1 月 1 日和 2020 年 3 月 31 日之间,则 (DATE_DIFF('2020-01-31',Order Date, DAY)) 否则为 0
Question -> how to use this condition statement in BigQuery?问题 -> 如何在 BigQuery 中使用这个条件语句?

Table - Customer ID |- 客户 ID | Order Date 298 |订购日期 298 | 2020-02-28 78 | 2020-02-28 78 | 2020-04-02 31 | 2020-04-02 31 | 2021-01-09 345 | 2021-01-09 345 | 2021-09-09 74 | 2021-09-09 74 | 2020-01-20 2020-01-20

I tried -我试过了 -

if((Order Date <'2020-01-01') and (Order Date >'2020-03-31'),(DATE_DIFF('2020-01-31' ,Order Date,  DAY)
,0))

Try below syntax: Once able to run it.尝试以下语法:一旦能够运行它。 Replace current_date with Order_Date.将 current_date 替换为 Order_Date。 Hope this will work.希望这会奏效。


select 

if(current_date <'2020-01-01' and current_date >'2020-03-31' ,DATE_DIFF('2020-01-31' ,current_date,  DAY),0);

在此处输入图像描述

Try SELECT statement with WHERE clause:尝试使用 WHERE 子句的 SELECT 语句:

SELECT id, orderdate, DATE_DIFF('2020-01-31', orderdate, DAY) as datediff FROM `yourdataset.ordertable`
WHERE orderdate BETWEEN '2020-01-01' AND '2020-03-31';

Output: Output:

id  orderdate   datediff
298 2020-02-28  -28
74  2020-01-20  11

CASE statement:案例声明:

SELECT 
  id, 
  orderdate,
  CASE 
      WHEN (orderdate BETWEEN '2020-01-01' AND '2020-03-31') THEN DATE_DIFF('2020-01-31', orderdate, DAY)
      ELSE 0
END AS `datediff`
FROM `yourdataset.ordertable`

Output: Output:

id  orderdate   datediff
78  02/04/20    0
298 28/02/20    -28
345 09/09/21    0
31  09/01/21    0
74  20/01/20    11

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM