mysql 如何获取给定列值之后的所有列值,直到找到指定的值

0kjbasz6  于 2023-05-05  发布在  Mysql
关注(0)|答案(2)|浏览(128)

嗨,在上表中,我想在col3中的特定列值之后更新所有派生列的值,例如在col3中,每当值Val1出现时,我们必须将派生列的值更新为val1,并将所有后续行更新为val1,直到col3值为Val2。当col3的值为Val2时,所有列及其下一个值将被更新为null,直到col3的值为val1。
请帮助我的sql逻辑

qij5mzcb

qij5mzcb1#

对于MySQL 8.x,我们可以在col3= val1 or val2中使用递增1的运行和来对数据进行分组,然后在nullif函数中使用条件max window函数来只获得val1和null而不是val2。获得正确的结果(使用CTE)后,使用带有联接的更新来更新表。

with cte as
(
  select col1, 
    nullif(max(case when col3 in ('Val1', 'Val2') then col3 else null end) over (partition by grp), 'Val2') der 
  from(
    select *,
    sum(col3 in ('Val1', 'Val2')) over (order by col1) grp
    from table_name
  ) t
)
update table_name tb join cte 
  on tb.col1 = cte.col1
  set derivied_col = cte.der

demo

4ngedf3f

4ngedf3f2#

UPDATE your_table t1
SET
    t1.Derived1 = 
        CASE
            WHEN t1.Col3 = 'Val1' THEN 'Val1'
            WHEN t1.Col3 = 'Val2' THEN NULL
            ELSE t1.Derived1
        END,
    t1.Derived2 = 
        CASE
            WHEN t1.Col3 = 'Val1' THEN 'Val1'
            WHEN t1.Col3 = 'Val2' THEN NULL
            ELSE t1.Derived2
        END,
    t1.Derived3 = 
        CASE
            WHEN t1.Col3 = 'Val1' THEN 'Val1'
            WHEN t1.Col3 = 'Val2' THEN NULL
            ELSE t1.Derived3
        END
WHERE 
    t1.Col3 IN ('Val1', 'Val2') OR 
    (t1.Derived1 = 'Val1' OR t1.Derived2 = 'Val1' OR t1.Derived3 = 'Val1')
ORDER BY t1.Col1, t1.Col2;

相关问题