我有一个查询,其中我对日期=昨天(current_date-1)的列中的值求和:
SELECT sum(col) as sumCol
from `project.dataset.table`
where date = date_sub(current_date, interval 1 day)
我想要实现的是计算上述结果与同一查询的前一天结果之间的差异,即date = date_sub(current_date,interval 2 day)
我不确定如何在查询中创建此计算。我可以将上述内容与前一天的相同查询进行合并,但是很显然,每天都会给我一行,而不是计算间隔1天-间隔2天的总和(col)?
如果能为我指出正确的方向,请提供帮助
谢谢
答案 0 :(得分:2)
好吧,您可以使用条件聚合:
select sum(case when date = date_sub(current_date, interval 1 day) then col else - col end) as diff
from `project.dataset.table`
where date in ( date_sub(current_date, interval 1 day), date_sub(current_date, interval 2 day) )
编辑:
通常,您可以使用条件聚合来获得两个值:
select sum(case when date = date_sub(current_date, interval 1 day) then col end) as yesterday,
sum(case when date = date_sub(current_date, interval 2 day) then col end) as day_before
from `project.dataset.table`
where date in ( date_sub(current_date, interval 1 day), date_sub(current_date, interval 2 day) )
然后可以按需要组合这些列。如果缺少某个值,则为NULL
,因此可以安全地进行除法和丢失值。
答案 1 :(得分:0)
您是否发现以下类似内容
SELECT
( sum(col) as sumCol
from `project.dataset.table`
where date = date_sub(current_date, interval 1 day)
)-( sum(col) as sumCol
from `project.dataset.table`
where date = date_sub(current_date, interval 2 day)
) from project.dataset.table