或带有计算日期的条件不起作用

时间:2019-08-29 06:51:57

标签: sql google-bigquery

尝试建立移动平均线,所以我正在尝试这样做(是的,我知道“前6行与当前行之间有行”,但这不是问题)。

该代码可与OR business_date ='2019-08-27'一起使用,但不适用于以下情况。

with x AS(
select
business_date
,TIMESTAMP_SUB(business_date, INTERVAL 24 HOUR) AS r1
,TIMESTAMP_SUB(business_date, INTERVAL 48 HOUR) AS r2
,TIMESTAMP_SUB(business_date, INTERVAL 72 HOUR) AS r3
,TIMESTAMP_SUB(business_date, INTERVAL 96 HOUR) AS r4
,TIMESTAMP_SUB(business_date, INTERVAL 120 HOUR) AS r5
,TIMESTAMP_SUB(business_date, INTERVAL 144 HOUR) AS r6
FROM `sometable`
)
select 
business_date
from x
WHERE business_date = '2019-08-28' OR business_date = r1
group by business_date

2 个答案:

答案 0 :(得分:0)

通过您提供的输入和内部查询,它将使用UNION返回2行。 由于cte的内部查询正在为每一行创建6 columns。记住创建6列,这样您将获得列而不是行。

with x AS(
select
business_date
,TIMESTAMP_SUB(business_date, INTERVAL 24 HOUR) AS r1
,TIMESTAMP_SUB(business_date, INTERVAL 48 HOUR) AS r2
,TIMESTAMP_SUB(business_date, INTERVAL 72 HOUR) AS r3
,TIMESTAMP_SUB(business_date, INTERVAL 96 HOUR) AS r4
,TIMESTAMP_SUB(business_date, INTERVAL 120 HOUR) AS r5
,TIMESTAMP_SUB(business_date, INTERVAL 144 HOUR) AS r6
FROM `sometable`
)
select business_date from x
WHERE business_date = '2019-08-28' or  business_date = r1
group by business_date 
union  
select r1 from x
WHERE business_date = r1 or  business_date = '2019-08-28'
group by business_date

答案 1 :(得分:0)

您似乎想有条件地取消日期设置。逻辑似乎是这样的:

SELECT r_date
FROM (SELECT timestamp('2019-08-28') as business_date) t CROSS JOIN
     UNNEST(ARRAY[business_date,
                  TIMESTAMP_SUB(business_date, INTERVAL 24 HOUR),
                  TIMESTAMP_SUB(business_date, INTERVAL 48 HOUR),
                  TIMESTAMP_SUB(business_date, INTERVAL 72 HOUR),
                  TIMESTAMP_SUB(business_date, INTERVAL 96 HOUR),
                  TIMESTAMP_SUB(business_date, INTERVAL 120 HOUR),
                  TIMESTAMP_SUB(business_date, INTERVAL 144 HOUR) 
                 ]
           ) r_date WITH OFFSET n
WHERE n IN (0, 1);