SQL Server Compare value between row and increment another column

x8goxv8g  于 2023-10-15  发布在  其他
关注(0)|答案(3)|浏览(111)

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 :

IdColumn AColumn BColumn DiffValue
130000
24001100
340010
45002100
5550350

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 ?

6jygbczu

6jygbczu1#

You can do a running conditional COUNT over the LAG . You seem to be using the wrong ORDER BY column, you need ORDER BY Id . And then update the CTE directly, you don't need to rejoin.

WITH PrevValues AS (
    SELECT mt.*, 
      Diff = mt.A - LAG(mt.A) OVER (ORDER BY mt.Id)
    FROM MyTable mt
),
Counted AS (
    SELECT t.*,
      Count = COUNT(CASE WHEN DiffValue > 0 THEN 1 END) OVER (ORDER BY t.Id ROWS UNBOUNDED PRECEDING)
    FROM PrevValues t
)
UPDATE Counted
SET DiffValue = Diff,
    ColumnB = Count;
ct3nt3jp

ct3nt3jp2#

Thank you @siggemannen it's a good answer, I just change 'when lag(a) < a by 'DiffValue > 0'

select * from (select sum(flag) over(order by id) as running, * from (select case when DiffValue > 0 then 1 else 0 end as flag, * from yourtable) x) x) x
7gs2gvoe

7gs2gvoe3#

Here, I compose an SQL for a similar situation.

Select *
INTO #Tmp1
FROM
(
    SELECT ID,
           [Column A],
           [Column B],
           LAG([Column A], 1) OVER (ORDER BY ID) Prev_Value
    from table1
) A

UPDATE t1
SET t1.[Column DiffValue] = (ISNULL(t2.[Column A] - t2.Prev_Value, 0))
FROM table1 t1
    INNER JOIN #Tmp1 t2
        ON t1.ID = t2.ID
drop table if exists #Tmp1

select * from table1

Another Example without using Temporary table.

UPDATE t1
SET t1.[Column DiffValue] = t2.Diff_Value
FROM table1 t1
INNER JOIN 
(
    SELECT ID,
           [Column A],
           [Column B],
           (ISNULL([Column A]-LAG([Column A], 1) OVER (ORDER BY ID),0)) Diff_Value
    from table1
) t2
    ON t1.ID = t2.ID

SELECT * FROM TABLE1

相关问题