简体   繁体   中英

Compare current row value with previous row values in loop in SQL

I have a table with fields - A (ID), B (Flag). I need to add a new column - C (Result) in this table and it's value will be derived based on B (Flag) field. If flag is false then keep checking previous rows till we get flag as true and then take value of A (ID) field and populate it in C (Result) column. So C will have the last value of A with B field as True.

Required Table

A B C
1 T 1
2 F 1
3 F 1
4 T 4
5 T 5
6 F 5
7 T 7
8 F 7
9 F 7
10 F 7
11 T 11
WITH
cte1 AS (
    SELECT A, SUM(B='T') OVER (ORDER BY A) group_no
    FROM test
),
cte2 AS (
    SELECT A, MIN(A) OVER (PARTITION BY group_no) previous_T
    FROM cte1
)
UPDATE test
JOIN cte2 USING (A)
SET test.C = cte2.previous_T;

https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=46c1edfbc42e331f9bb39a36ea71e905

In MySQL 5.x use

UPDATE test
JOIN (
    SELECT A, 
           @tmp := CASE WHEN B='T' THEN A ELSE @tmp END C
    FROM test
    JOIN (SELECT @tmp:=0) init
    ORDER BY A
) data USING (A)
SET test.C = data.C;

https://dbfiddle.uk/?rdbms=mysql_5.7&fiddle=3f341b98b768c2a2369b5d814453b234

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM