【问题标题】:How to add the missing months name to the sql table in sequence by checking the previous month name?如何通过查看上月名,将缺失的月份名依次添加到sql表中?
【发布时间】:2021-12-20 22:04:53
【问题描述】:

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

创建表的代码:

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

【问题讨论】:

  • 您只需要 SQL 中的解决方案吗?您可以在将缺失值插入数据库之前更正它
  • cust_id 是指月数吗?
  • @Phil Coulson,不,它指的是序列号,只是 101,102 之类的 id 等

标签: mysql sql mysql-workbench


【解决方案1】:
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

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

【讨论】:

    【解决方案2】:
    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;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-09-27
      • 2017-07-23
      • 1970-01-01
      • 1970-01-01
      • 2013-06-24
      • 1970-01-01
      相关资源
      最近更新 更多