Search code examples
sqlrowsubtraction

SQL - subtraction row


I have the following query

SELECT VALUE
    ,Source1
    ,Source2
    ,DocNo
FROM myTable

it returns the below data:

enter image description here

I want to calculate the subtraction based on the below condition:

for DocNo A1
if(Source1=1 and Source2=0) VALUE 34
if(Source1=1 and Source2=0) VALUE 21
subtraction  two row 34 - 21 = 13 

Any idea?

Expected result:

enter image description here


Solution

  • If I understand your issue correctly, the query below is you want:

    SELECT Value, Score1, Score2, DocNo
    FROM TestTable 
    WHERE Score1 = 0
    
    UNION 
    
    SELECT MAX(Value) - MIN(Value) AS Value, 1, 1, DocNo
    FROM TestTable 
    WHERE Score1 = 1
    GROUP BY DocNo
    ORDER BY DocNo, Score1
    

    DEMO for the same.