简体   繁体   English

Maria DB - 使用前一行的值更新行+常量

[英]Maria DB - update row with value of previous row + constant

I have table called dobridol with several column.我有几列名为dobridol的表。

CREATE TABLE IF NOT EXISTS `dobridol` (
  `id` int(6) unsigned NOT NULL,
  `dt` varchar(200)  NOT NULL,
  `p2` int(6) NOT NULL,
  `p6` int(6) NOT NULL,
  PRIMARY KEY (`id`)
) DEFAULT CHARSET=utf8;

INSERT INTO `dobridol` (`id`, `dt`, `p2`,`p6`) VALUES
  ('1', '2021-02-28 23:50:00', '100', '600'),
  ('2', '2021-02-28 23:55:00', '200', '700'),
  ('3', '2021-03-01 00:00:00', '300', '800'),
  ('4', '2021-03-01 00:05:00', '400', '900'),
  ('5', '2021-03-01 00:10:00', '400', '900'),
  ('6', '2021-03-01 00:15:00', '400', '900'),
  ('7', '2021-03-01 00:20:00', '500', '1000'),
  ('8', '2021-03-01 00:25:00', '600', '1100');

The table has values for January and March also.该表还包含 1 月和 3 月的值。

I want to be able to UPDATE table like that:我希望能够像这样更新表:

I select period as month, then I add constant value (in this case I added 39) to p6 ONLY WHEN p2 value is different than previous row p2.我将 select 周期作为月份,然后仅当 p2 值与前一行 p2 不同时,我将常数值(在本例中我添加 39)添加到 p6。 If this is the case I have to add 39 to PREVIOUS row p6 value.如果是这种情况,我必须将 39 添加到 PREVIOUS 行 p6 值。

update dobridol join
       (select tt.*,
               sum(case when p2 <> prev_p2 then 1 else 0 end) over (order by dt) as cnt
        from (select tt.*,
                     lag(p2) over (order by dt) as prev_p2
              from dobridol tt
             ) tt
              
       ) tt
       on tt.id = dobridol.id       
       set dobridol.p6 = cnt * 39 + <PREVIOUS_ROW_p6_VALUE_HAS_TO_BE_HERE>
    where cnt > 0 

The query should look-like this but I have to replace this <PREVIOUS_ROW_VALUE_HAS_TO_BE_HERE> with the right syntax of picking last row p6.查询应该看起来像这样,但我必须用选择最后一行 p6 的正确语法替换这个 <PREVIOUS_ROW_VALUE_HAS_TO_BE_HERE>。 How can I pick it?我该如何挑选它?

Also where to add clause还有在哪里添加子句

dobridol.dt BETWEEN '2021-03-01' AND '2021-03-30'

in the SQL query?在 SQL 查询中?

If I understand correctly, you can use lag() :如果我理解正确,您可以使用lag()

update dobridol join
       (select tt.*,
               lag(p6) over (order by dt) as prev_p6,
               sum(case when p2 <> prev_p2 then 1 else 0 end) over (order by dt) as cnt
        from (select tt.*,
                     lag(p2) over (order by dt) as prev_p2
              from dobridol tt
             ) tt
       ) tt
       on tt.id = dobridol.id       
       set dobridol.p6 = tt.cnt * 39 + tt.prev_p6
    where cnt > 0 ;

Here is a db<>fiddle. 是一个 db<>fiddle。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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