Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Subtracting One Row From Another Row

Author  Topic 

goodyear
Starting Member

2 Posts

Posted - 2012-07-04 : 15:45:33
Hi Everyone,

I need help on how to subtract a value from a row on another row.

For example:

I have a simple table called "COST."

In my COST table I need to subtract the cost of Calif. - SoCal, so it would (2,000-500=1500).


--TABLE COST---

Location COST
ROW 1 Calif. 2,000
ROW 2 SoCAL 500


On my final output what I would ultimately want is to have the following.

Location COST
ROW 1 Calif. 2,000
ROW 2 SoCAL 500
Row 3 Calif_2 1,500


Is this possible? Thanks in advance!

My





visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2012-07-04 : 16:54:10
yep possible

SELECT *,t1.Cost AS PrevCost
FROM table t
OUTER APPLY (SELECT SUM(CASE WHEN Location LIKE 'Calif%' THEN COST ELSE -1 * COST END) AS Cost
FROM Table
WHERE PK < t.PK
)t1


------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page

goodyear
Starting Member

2 Posts

Posted - 2012-07-04 : 20:44:03
Thanks Visakh for responding.

I tried your suggestion, but and it error out. I'm not sure if it's my syntax or that OUTER APPLY is not recognized in Oracle.

CREATE TABLE GY_COST AS
SELECT *,t1.cost AS PrevCost
FROM table t
OUTER JOIN (SELECT SUM(CASE WHEN LOCATION LIKE 'CALIF%' THEN COST ELSE -1 * COST END) AS COST
FROM TABLE
WHERE ROWNUM<t.ROWNUM) t1;
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2012-07-04 : 23:37:16
you're in wrong forum then!
This is MS SQL Server forum so please post in Oracle forums like www.orafaq.com for Oracle related help.

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page
   

- Advertisement -