Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sum the values of a column for several rows?

I have this table, and I want to add the values of 'change' column for several rows (Or, to be more exact from the row in which 'ne' value is zero up to the next row which includes zero for 'ne' (not the second one itself)). Any answer would be appreciated.

┌─rn─┬───────date─┬─ne─┬───────change─┐
│  0 │ 2008-12-07 │  0 │ -10330848398 │
│  1 │ 2009-04-14 │  1 │       -61290 │
│  2 │ 2009-04-26 │  1 │   9605743360 │
│  3 │ 2013-07-06 │  0 │ -32028871920 │
│  4 │ 2014-01-12 │  1 │ -42296164902 │
│  5 │ 2015-06-08 │  1 │  59100383646 │
└────┴────────────┴────┴──────────────┘

The result we expect is something like this.

row    start        end         sum(change) 
--------------------------------------------------
0 | 2008-12-07 | 2009-04-26 | -725,166,328
--------------------------------------------------
1 | 2013-07-06 | 2015-06-08 | -15,224,653,176
--------------------------------------------------
like image 565
Commander Avatar asked Oct 24 '25 10:10

Commander


1 Answers

This is a gaps and islands problem. Canonical solutions do use window functions, which as far as concerns, Clickhouse does not support.

Here is one approach that uses a subquery to emulate a conditional window sum:

select
    min(date) start_date,
    max(date) end_date,
    sum(change) sum_change
from (
    select 
        t.*,
        (select count(*) from mytable t1 where t1.date <= t.date and t1.ne = 0) grp
    from mytable t
) t
group by grp

The subquery counts how many rows have ne = 0 from the first row of the table until the current row. This defines groups of records. Then all that is left to do is aggregate.

If you could use window functions, you would phrase this as:

select
    min(date) start_date,
    max(date) end_date,
    sum(change) sum_change
from (
    select 
        t.*,
        sum(case when ne = 0 then 1 else 0 end) over(order by date) grp
    from mytable t
) t
group by grp
like image 114
GMB Avatar answered Oct 27 '25 01:10

GMB