Search code examples
mysqlsqldata-analysis

How to reset running total for a column if null is present?


I have a table as below

Customer Start_Date_of_Month Sales_order_count Value
A 01/06/2022 3 null
B 01/07/2022 2 null
A 01/07/2022 0 1
A 01/08/2022 0 1
B 01/08/2022 0 1
A 01/09/2022 3 null
B 01/09/2022 1 null
A 01/10/2022 1 null
B 01/10/2022 0 1
A 01/11/2022 0 1

I'm trying to calculate the running total of Value column with respect to Customer and by Start_Date _of_Month in ascending order. If null is present in the Value column, the running total has to be reset

The output would be like

Customer Start_Date_of_Month Sales_order_count Running_Total
A 01/06/2022 3 null
A 01/07/2022 0 1
A 01/08/2022 0 2
A 01/09/2022 3 null
A 01/10/2022 1 null
A 01/11/2022 0 1
B 01/07/2022 2 null
B 01/08/2022 0 1
B 01/09/2022 1 null
B 01/10/2022 0 1

Thanks in Advance


Solution

  • You could define groups for each customer whenever a null value is found, then use the running sum partitioned by these groups, try the following for MySQL 8+:

    select Customer, Start_Date_of_Month, Sales_order_count,
      sum(Value) over (partition by Customer, grp order by Start_Date_of_Month) Running_Total
    from
    (
      select *,
        sum(value is null) over (partition by Customer order by Start_Date_of_Month) grp
      from table_name
    ) T
    order by Customer, Start_Date_of_Month  
    

    See demo