I have a table with a column A with a value smallint and I want compare if the value is greater than a last value in a same table. If this value is greater, I want increment a value in a column B.
Before request :
| Id | Column A | Column B |
| ------------ | ------------ | ------------ |
| 1 | 300 | 0 |
| 2 | 400 | 0 |
| 3 | 400 | 0 |
| 4 | 500 | 0 |
| 5 | 550 | 0 |
After request :
Id | Column A | Column B | Column DiffValue |
---|---|---|---|
1 | 300 | 0 | 0 |
2 | 400 | 1 | 100 |
3 | 400 | 1 | 0 |
4 | 500 | 2 | 100 |
5 | 550 | 3 | 50 |
Actually I have this code for compared the value between two row but I'm blocked now.. Code :
UPDATE tA
SET tA.DiffValue =tB.DiffValue,
FROM MyTable as tA
INNER JOIN(
SELECT Id, DiffValue = A - LAG(A) OVER (ORDER BY A ASC)
FROM MyTable
) as tB ON tA.Id = tB.Id
Do you have any solution ?
3条答案
按热度按时间6jygbczu1#
You can do a running conditional
COUNT
over theLAG
. You seem to be using the wrongORDER BY
column, you needORDER BY Id
. And then update the CTE directly, you don't need to rejoin.ct3nt3jp2#
Thank you @siggemannen it's a good answer, I just change 'when lag(a) < a by 'DiffValue > 0'
7gs2gvoe3#
Here, I compose an SQL for a similar situation.
Another Example without using Temporary table.