如何通过检查上个月名称将缺少的月份名称依次添加到sql table?

How to add the missing months name to the sql table in sequence by checking the previous month name?

我想将缺少的月份添加到 table。如果当前行缺少月份,那么它应该检查前一行和该行中的月份名称,并在当前行中添加下一个月。 例如:当前月份为null,它应该检查上一行中的月份名称,如果上一行有January那么当前月份应该用February替换null, 例如。如果当前月份为空,则应检查前一行中的月份名称是否为八月,然后下一个空月份名称应替换为九月。

创建代码 table:

CREATE TABLE IF NOT EXISTS missing_months (
    `Cust_id` INT,
    `Month` VARCHAR(9) CHARACTER SET utf8,
    `Sales_value` INT
);
INSERT INTO missing_months VALUES
    (1,'Janurary',224),
    (2,'February',224),
    (3,NULL,239),
    (4,'April',205),
    (5,NULL,218),
    (6,'June',201),
    (7,NULL,205),
    (8,'August',246),
    (9,NULL,218),
    (10,NULL,211),
    (11,'November',223),
    (12,'December',211);

输出为:

 Cust_id    Month     Sales_value
    1       Janurary    224
    2       February    224
    3       null        239
    4       April       205
    5       null        218
    6       June        201
    7       null        205
    8       August      246
    9       null        218
    10      null        211
    11      November    223
    12      December    211

但我想要这样的输出:

   Cust_id  Month       Sales_value
    1       Janurary    224
    2       Febrauary   224
    3       March       239
    4       April       205
    5       May         218
    6       June        201
    7       July        205
    8       August      246
    9       September   218
    10      October     211
    11      November    223
    12      December    211
update missing_months m
join missing_months prev on prev.Cust_id=m.Cust_id-1
set m.Month=date_format(str_to_date(concat(prev.Month,'-1970-01'),'%M-%Y-%d') + interval 1 month,'%M')
where m.Month is null
order by m.Cust_id

但是依靠标识符字段进行排序是不好的;如果您的数据是有序的,您应该有一些其他列来指示顺序是什么。

select Cust_id, monthname(STR_TO_DATE(rn, '%m')) as Month_Name, 
Sales_value 
from
        (Select Cust_id, Month, row_number() over() as rn,
        Sales_value 
        from missing_month) x;