我需要查询以将一个星期六的总销售额与该年度剩余的平均星期六的总销售额进行比较

时间:2019-11-29 13:19:35

标签: sql date google-bigquery

我的数据集的字段是ts,数量,单价

我首先需要运行sum(quanitiy * unit_price)以获得我的销售号码

ts(时间戳)的格式如下-2019-01-15 14:55:00 UTC

2 个答案:

答案 0 :(得分:1)

这是您想要的吗?

select avg(case when datecol = ? then total end) as sales_your_date,
       avg(case when datecol <> ? then total end) as sales_other       
from (select date(t.ts) as dte, sum(t.quantity * t.unit_price) as total
      from t
      where ts >= timestamp('2018-01-01') and
            ts < timestamp('2019-01-01')
      group by dte
     ) t
where extract(dayofweek from datecol) = 6  -- Saturday

这与您之前的问题没有太大不同。相同的想法起作用,只是首先汇总数据。

?是您关心的日期。

答案 1 :(得分:0)

以下是用于BigQuery标准SQL

#standardSQL
SELECT DATE(ts) AS sale_date, quanitiy * unit_price AS sale_total, 
  ROUND((SUM(quanitiy * unit_price) OVER() - quanitiy * unit_price) / (COUNT(1) OVER() - 1), 2) AS sale_rest_average
FROM `project.dataset.table`
WHERE EXTRACT(DAYOFWEEK FROM DATE(ts)) = 7
AND EXTRACT(YEAR FROM DATE(ts)) = 2018  

如果您的时间戳字段是TIMESTAMP数据类型(相对于STRING),则只能使用

WHERE EXTRACT(DAYOFWEEK FROM ts) = 7
AND EXTRACT(YEAR FROM ts) = 2018