I have the following table
+------------+----------+------------+ | SaleDate | SaleName | SaleAmount | +------------+----------+------------+ | 2021-03-01 | Jack | 40 | | 2021-03-02 | Mark | 60 | | 2021-03-03 | Sam | 30 | | 2021-03-03 | Mark | 70 | | 2021-03-02 | Sam | 100 | | 2021-03-01 | Jack | 70 | +------------+----------+------------+
I want to find the date-wise cumulative SalesAmount, while also maintaining the increasing count of salesman names that come into the table.
+------------+-----------------+-----------------+ | SaleDate | Count(SaleName) | Sum(SaleAmount) | +------------+-----------------+-----------------+ | 2021-03-01 | 1 | 110| | 2021-03-02 | 3 | 270| | 2021-03-03 | 3 | 370| +------------+-----------------+-----------------+
So basically the task is to eliminate the duplicate names, that may occur on the daily basis, or in a cumulative fashion?
Advertisement
Answer
You can use a window function to get the first date a sales person appears. Then use aggregation and a cumulative sum:
select saledate, sum(sum(case when seqnum = 1 then 1 else 0 end)) over (order by saledate), sum(sum(amount)) over (order by saledate) as running_amount from (select t.*, row_number() over (partition by salename order by saledate) as seqnum from t ) t group by saledate order by saledate;