sum last n days quantity using sql window function

二次信任 提交于 2021-02-11 13:36:56

问题


I am trying to create following logic in Alteryx and data is coming from Exasol database.

Column “Sum_Qty_28_days“ should sum up the values of “Qty ” column for same article which falls under last 28 days.

My sample data looks like:

and I want following output:

E.g. “Sum_Qty_28_days” value for “article” = ‘A’ and date = ‘’2019-10-8” is 8 because it is summing up the “Qty” values associated with dates (coming within previous 28 days) Which are: 2019-09-15 2019-10-05 2019-10-08 for “article” = ‘A’.

Is this possible using SQL window function? I tried myself with following code:

SUM("Qty") OVER (PARTITION BY "article", date_trunc('month',"Date")
             ORDER BY "Date")

But, it is far from what I need. It is summing up the Qty for dates falling in same month. However, I need to sum of Qty for last 28 days.

Thanks in advance.


回答1:


Yes, this is possible using standard SQL and in many databases. However, this will not work in all databases:

select t.*,
       sum(qty) over (partition by article
                      order by date
                      range between interval '27 day' preceding and current row
                     ) as sum_qty_28_days
from t;



回答2:


If your RDBMS does not support the range frame, an alternative solution is to use an inline subquery:

select 
    t.*,
    (
        select sum(t1.qty) 
        from mytable t1 
        where 
            t1.article = t.article
            and t1.date between t1.date - interval 28 days and t1.date
    ) sum_qty_28_days
from mytable t


来源:https://stackoverflow.com/questions/59249373/sum-last-n-days-quantity-using-sql-window-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!