I've been stumped with some SQL where I've got several rows of data, and I want to subtract a row from the previous row and have it repeat all the way down.
So here is the table:
CREATE TABLE foo ( id, length )
INSERT INTO foo (id,length) VALUES(1,1090) INSERT INTO foo (id,length) VALUES(2,888) INSERT INTO foo (id,length) VALUES(3,545) INSERT INTO foo (id,length) VALUES(4,434) INSERT INTO foo (id,length) VALUES(5,45)
I want the results to show a third column called difference which is one row subtracting from the one below with the final row subtracting from zero.
+------+------------------------+ | id |length | difference | +------+------------------------+ | 1 | 1090 | 202 | | 2 | 888 | 343 | | 3 | 545 | 111 | | 4 | 434 | 389 | | 5 | 45 | 45 |
I've tried a self join but I'm not exactly sure how to limit the results instead of having it cycle through itself. I can't depend that the id value will be sequential for a given result set so I'm not using that value. I could extend the schema to include some kind of sequential value.
This is what I've tried:
SELECT id, f.length, f2.length, (f.length - f2.length) AS difference FROM foo f, foo f2
Thank you for the assist.
The Minus Operator in SQL is used with two SELECT statements. The MINUS operator is used to subtract the result set obtained by first SELECT query from the result set obtained by second SELECT query.
In the blue text, you can see the calculation of the SQL delta between two rows. To calculate a difference, you need a pair of records; those two records are “the current record” and “the previous year's record”. You obtain this record using the LAG() window function.
MINUS compares the data in two tables and returns only the rows of data using the specified columns that exist in the first table but not the second. It would be possible to get all of the results from the second table that don't exist in the first by switching the table order in the query.
This might help you (somewhat).
select a.id, a.length,
coalesce(a.length -
(select b.length from foo b where b.id = a.id + 1), a.length) as diff
from foo a
Yipee!!! this does the trick:
SELECT f.id, f.length,
(f.length - ISNULL(f2.length,0)) AS diff
FROM foo f
LEFT OUTER JOIN foo f2
ON f2.id = (f.id +1)
Please check for other cases also, it is working for the values you posted! Note this is for SQL Server 2005
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With