Search code examples
sqlsql-servert-sqlsumwindow-functions

SQL Partition By to calculate Net Value


Imagine an order system, with multiple orders having sides as Buy and Sell. The data set look like this

Sample Structure

I want to calculate the Net Value which is (Sum of All Buy Sides - Sum of All Sell Sides)

Expected output:

Expected

I have currently used Partition By to arrive at following output

SELECT 
[NAME]
,[Side]
,[Value]
,SUM([Value]) OVER (PARTITION BY [NAME],[Side]) as Net
FROM 
[Order]

Output:

enter image description here

But I am not getting how to subtract the values and arrive at the expected result.


Solution

  • You can use window functions with conditional logic

    select
        t.*,
        sum(case side when 'B' then value when 'S' then -value end) 
            over(partition by name) net
    from mytable t