I’m writing a query on SQL Server and have hit a wall on cumulative sum with multiple conditions.
I need to sum all the purchases in a day made by a user, I can do it separately, sum purchases by day(Daily_Total), or sum purchases by user(User_Total), but I run into a wall when I need both conditions met(User_Daily_Total). I tried using GROUP BY, WHERE and HAVING clauses, but it’s never the right solution. If anyone can help I’d be so grateful.
Where I tried:
select UserID, CreateDate, Sale, sum(Sale) over (partition by UserID) as User_Total, sum(Sale) over (partition by CreateDate) as Daily_Total from table
This is what I need my table to look like, I have everything but the last column, which is where I’m stuck. Help?
Table:
Advertisement
Answer
For the last column you need to partition by both columns, as in:
select UserID, CreateDate, Sale, sum(Sale) over (partition by UserID) as User_Total, sum(Sale) over (partition by CreateDate) as Daily_Total, sum(Sale) over (partition by UserID, CreateDate) as User_Daily_Total from table