SQL Daily Outstanding Sales, Rolling Aggregate?

烈酒焚心 提交于 2021-01-28 09:08:17

问题


With the below test data I am trying to show how many sales have not been actioned by a colleague, an outstanding sale is any record that is still showing as "New", I have been using the below to identify those.

select saleID, count(*) group by saleID having count(*)=1

The trouble I have is that I find it easy to show overall how many are still outstanding to date but I can't figure out how to show how many were outstanding say 3 days ago. The idea is that this will show a trend when charted daily which will highlight if there has been an increase/decrease of outstanding sales by the end of each day. Ideally the output would be along the lines of the below

   Date      VolumeOutstanding 
2020-01-01    0
2020-01-02    1
2020-01-03    3
2020-01-04    2    

DataSet

SaleID   Date         Outcome
1        2020-01-01   New
1        2020-01-01   Complete
2        2020-01-01   New
2        2020-01-02   Complete
3        2020-01-03   New
4        2020-01-03   New
5        2020-01-03   New
5        2020-01-04   Complete

回答1:


You can use conditional aggregation and a cumulative sum:

select date,
       sum(sum(case when outcome = 'New' then 1
                    when outcome  'Complete' then -1
                    else 0
               end)
           ) over (order by date) as VolumeOutstanding
from t
group by date
order by date;

This assumes that each saleId has at most one "new" and one "complete" record -- which makes sense and is true in your sample data.



来源:https://stackoverflow.com/questions/61797669/sql-daily-outstanding-sales-rolling-aggregate

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