我如何询问一周的百分比变化

时间:2018-12-16 08:36:53

标签: sql google-bigquery

我需要在X天取一个值,在X-7天取第二个值,然后计算%。 该查询可能类似于:

select
  edate, count_today, count_lastweek,
  round(
    100.0 * (count_today - count_lastweek) / count_lastweek, 2
  )  as daily_delta
from (
select
   EXTRACT(date FROM ts) as  edate,
    count(1) count_today,
    lag(count(1), 7) over (order by 1) as count_lastweek
  from X
  group by 1
  order by 1 desc
  limit 7) t

上周的结果不正确,试图了解原因 谢谢!

1 个答案:

答案 0 :(得分:1)

我对此查询一无所知。如果您使用lag(),则假定您每天都有数据。让我做个假设。

我希望查询如下:

select date(ts) as edate, count(*) as cnt,
       (1 - cnt / lag(count(*), 7) over (order by date(ts))) as one_week_increase
from s
group by date(ts)
order by edate desc