In SQL Server 2005, I would do this using a correlated subquery:
select dummy_id, date_registered, item_id, quantity, price,
(select sum(quantity)
from t t2
where t2.item_id = t.item_id and
t2.date_registered <= t.date_registered
) as cumulative
from table t;
If you actually want to add this into a table, you need to alter the table to add the column and then do an update. If the table has inserts and updates, you will need to add a trigger to keep it up-to-date. Getting it through a query is definitely easier.
In SQL Server 2012, you can do this using the syntax:
select dummy_id, date_registered, item_id, quantity, price,
sum(quantity) over (partition by item_id order by date_registered) as cumulative
from table t;
Answer from Gordon Linoff on Stack OverflowCumulative Sum by multiple groups
postgresql - Grouping data based on cumulative sum - Database Administrators Stack Exchange
sql - How to get cumulative sum by group - Stack Overflow
sql server - SQL Query for cumulative sum - Database Administrators Stack Exchange
You can combine it like this
select month,
sum(sales) as month_sales,
sum(sum(sales)) over (order by month) as cum_sum
from sales
group by month
db<>fiddle demo
Note : this works for SQL Server and MySQL. Tested on fiddle
We can try to use a subquery to calculate total sales each month before sum window function.
SELECT t1.*,sum(total_sales) over(order by month) as cum_sum
FROM (
select month, sum(sales) total_sales
from sales
group by month
) t1
Hello!
I am trying to write a SQL query using a combination of CTE and windows function to calculate a cumulative sum of the count of product.
My apologize as I'm using my mobile but here is an example of the dataset
Productcode RATE1 RATE1 RATE3 RATE1 RATE3 RATE2
The original table has a lot of columns but I'm only interested into 1. It also has customer id but a customer can only have 1 product. There is also date row but I'm not interested in the date
I wrote the below with the idea of taking a column out of many from the original dataset, group the product code and get individual count of each rate and finally add a column running a cumulative sum
WITH testtable AS (Select Productcode ,Count(*) as Freq From table group by 1) Select Productcode ,Sum(Freq) over (partition by productcode) as cumul From testtable
The output is essentially a duplicate of the column Freq as opposed to the cumulative Freq as I hoped.
I also appreciate that there is certainly an easier way of getting this done but I still would like to know why it is not working?
Thanks for your inputs!
Edit: moved 'AS' to the correct position Edit 2: sample dataset and further clarifications Edit 3: solved SUM(COLUMN) OVER (ORDER BY productid)