Reputation: 11972
I want to find the difference between two rows on the same column group by id
ID Value1 Value2
a 500 200
b 300 200
a 100 300
b 300 400
....
Expected output
ID Value1 Value2
a 400 -100
b 0 -200
....
How to make a query for the above condition.
Upvotes: 2
Views: 6472
Reputation: 16894
Use option with CTE and ROW_NUMBER() ranking function
;WITH cte AS
(
SELECT ID,
CASE ROW_NUMBER() OVER(PARTITION BY ID ORDER BY 1/0) % 2
WHEN 1 THEN Value1
WHEN 0 THEN -1 * Value1 END AS Value1,
CASE ROW_NUMBER() OVER(PARTITION BY ID ORDER BY 1/0) % 2
WHEN 1 THEN Value2
WHEN 0 THEN -1 * Value2 END AS Value2
FROM dbo.test22
)
SELECT ID, SUM(Value1) AS Value1, SUM(Value2) AS Value2
FROM cte
GROUP BY ID
Demo on SQLFiddle
Upvotes: 0
Reputation: 32445
This query will give a absolute difference between max value of ID and min value of same ID:
SELECT ID
, ABS(MAX(VALUE1) - MIN(VALUE1)) AS v1Diff
, ABS(MAX(VALUE2) - MIN(VALUE2)) AS v2Diff
FROM TABLE1
GROUP BY ID
But if you want get a real difference(negative diff) then we need to know which row is first and which row is next. Then we can count difference like firstRowValue - nextRowValue
.
Maybe your table has some RowID
or DateTime
column from where we can ordering a rows from same ID
.
What column/columns are Primery Key
in your table?
Upvotes: 0
Reputation: 4892
You can try:
SELECT t1.ID, max(t2.VALUE1 - t1.VALUE1)
FROM TABLE1 t1
left join TABLE1 t2 on t1.id = t2.id
group by t1.id
Upvotes: 2
Reputation: 125610
You can use following:
SELECT
ID,
MAX(Value1) - MIN(Value1),
MIN(Value2) - MAX(Value2)
FROM
myTableName
GROUP BY
ID
But there is one assumption: the second row has always greater Value1
and lower Value2
than first one.
Upvotes: 3