【问题标题】:Running total sum over date presto SQL在日期 presto SQL 上运行总和
【发布时间】:2019-09-30 00:26:02
【问题描述】:

我正在尝试使用 Presto SQL 从下面的示例数据中计算一个日期内 t 和 s 列的累积总和。

Date   | T | S 
1/2/19 | 2 | 5
2/1/19 | 5 | 1
3/1/19 | 1 | 1

我想得到

Date   | T | S | cum_T | cum_S 
1/2/19 | 2 | 5 |    2  |  5 
2/1/19 | 5 | 1 |    7  |  6
3/1/19 | 1 | 1 |    8  |  7

但是,当我使用 Presto SQL 运行以下查询时,我收到了意外的错误消息,告诉我将列 T 和 S 放入查询的分组中。

这是预期的吗?当我从查询中删除 group by 时,它运行没有错误,但会产生重复的日期行。 +

select
  date_trunc('day',tb1.date),
  sum(tb1.S) over (partition by date_trunc('day',tb1.date) order by date_trunc('day',tb1.date) rows unbounded preceding )  as cum_S,
  sum(tb1.T) over (partition by date_trunc('day',tb1.date) order by date_trunc('day',tb1.date) rows unbounded preceding)  as cum_T
from esi_dpd_bi_esds_prst.points_tb1_use_dedup_18months_vw tb1
where 
  tb1.reason_id not in (45,264,418,983,990,997,999,1574)
  and tb1.group_id not in (22)
  and tb1.point_status not in (3)
  and tb1.date between cast(DATE '2019-01-01' as date) and cast( DATE '2019-01-03' as date)
group by 
    1
order by date_trunc('day',tb1.date) desc 

错误如下:

Error: line 3:1: '"sum"(tb1.S) OVER (PARTITION BY "date_trunc"('day', tb1.tb1) ORDER BY "date_trunc"('day', tb1.tb1) ASC ROWS UNBOUNDED PRECEDING)' must be an aggregate expression or appear in GROUP BY clause.

【问题讨论】:

    标签: sql presto


    【解决方案1】:

    您有一个聚合查询,并且希望将聚合与窗口函数混合。正确的语法是:

    select date_trunc('day', tb1.date),
           sum(tbl1.S) as S,
           sum(tbl1.T) as T,
           sum(sum(tb1.S)) over (order by date_trunc('day', tb1.date) rows unbounded preceding )  as cum_S,
           sum(sum(tb1.T)) over (order by date_trunc('day', tb1.date) rows unbounded preceding)  as cum_T
    from esi_dpd_bi_esds_prst.points_tb1_use_dedup_18months_vw tb1
    where tb1.reason_id not in (45, 264, 418, 983, 990, 997, 999, 1574) and
          tb1.group_id not in (22) and
          tb1.point_status not in (3) and
          tb1.date between cast(DATE '2019-01-01' as date) and cast( DATE '2019-01-03' as date)
    group by 1
    order by date_trunc('day', tb1.date) desc ;
    

    即窗口函数在聚合后运行,需要对聚合后的值进行处理。

    【讨论】:

    • 感谢您的回答。这运行没有错误,但产生了 cum_S 和 cum_T 的总和,而不是累积总和,col 2 等于 col 4,col 3 等于 col 5。
    • @user124123 。 . .我在计算中留下了您的 partition by 子句。这显然没有必要——你想按日期排序,而不是按日期分区。
    • 是的,现在可以了,我不太确定我是否理解你在代码之后的解释,你知道我可以查看任何资源来更详细地解释这个吗?
    • @user124123 。 . .如果您了解窗口函数,那么只需练习使用聚合窗口函数即可。
    • @alwaysaskingquestions 。 . .没有。一个sum() 用于聚合。第二个是窗口函数。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-14
    • 1970-01-01
    • 2022-01-17
    • 2019-11-20
    • 2021-12-06
    • 2020-06-05
    相关资源
    最近更新 更多