I want to display the subtraction of two values from two different rows using a SQL query.
This is the table structure:
id | Value|
-----------
1 | 20 |
2 | 30 |
3 | 50 |
4 | 70 |
5 | 100 |
Output should be as follows.
id | Value| Difference |
------------------------
1 | 20 | Null |
2 | 30 | 10 |
3 | 50 | 20 |
4 | 70 | 20 |
5 | 100 | 30 |
I have a solution for SQL Server
and I expect the ones for Oracle and MySQL to be very similar.
Note: Id
s do not have to be contigous, but I use them for ordering the results.
Setup:
-- drop table dbo.testVals
CREATE TABLE dbo.testVals (
Id INT,
Value INT
)
GO
-- truncate table dbo.testVals
INSERT INTO dbo.testVals (Id, Value)
VALUES (1, 20), (2, 30), (3, 50), (4, 70), (5, 100)
GO
SQL Server 2008 R2 solution:
;WITH cte as (
SELECT Id, Value, ROW_NUMBER() OVER (ORDER BY Id) AS RowNo
FROM dbo.testVals
)
SELECT r1.Id, r1.Value, r1.Value - r2.Value
FROM cte r1
LEFT JOIN cte r2 ON r2.RowNo = r1.RowNo - 1
GO
SQL Server 2012 solution: (we have LAG and LEAD functions there)
SELECT Id, Value, Value - LAG(Value, 1, NULL) OVER (ORDER BY Id)
FROM dbo.testVals
GO
Oracle has LAG and LEAD functions. MySQL does not seem to have them, so you should use something similar to the first query.
Try this:
SELECT t1.id, t1.value,
CASE t2.value WHEN NULL THEN NULL ELSE (t1.value - t2.value) END AS Difference
FROM mytable t1 LEFT JOIN mytable t2 ON t1.id = (t2.id + 1) ORDER BY t1.id
see sqlfiddle
Another approach
SELECT id, VALUE, (VALUE - previousValue) AS difference FROM (
SELECT id, VALUE, @prevValue previousValue , @prevValue := `VALUE` FROM `mytable`
JOIN (SELECT @prevValue := NULL) a
ORDER BY id ) b;
See the Fiddle
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.