5

I have a Layer "SplitNEW" which is grouped by the "group"-Column as follow: 0-RED , 1-GREEN , 3-BLUE.

My Data

The 3 Lines where previous split. Each Row in attribute table stands for an line segment as selected ( just for visualization purposes ). Each segment has a value "sum_in_kW" wich was aggregated from another Layer. I assigned for each segment in his group an segment id ("seg_id") and it iterate it ( order from top to bottom of the line - direction of the line ).

What i would like to do is sum up the column "sum_in_kw" for the current segment and and the segment before the current segment ( filter: per group ).

I allready have a solutin but this involves "Split vector Layer" by the column "group" resulting in 3 Layers ( in reality i deal with much more groups). For each Layer by BatchProcess I would add an column "sum_segement" with the following aggregate:

aggregate(@layer_name, 'sum', "sum_in_kW", "seg_id"<=attribute(@parent, 'seg_id'))

After that I can merge all the Layers back.

enter image description here

My question: Is there any way to use an aggregate or some other function as needed to sum up the segments in the right order of "seg_id" and adding somehow a filter to perform this per "group".

2 Answers 2

7

You can create a virtual layer that will compute this field. You can then export it to a new permanent layer if you wish to persist the result.

Go to the menu Layer > Add Layer > Add/Edit Virtual Layer... and enter the following query. Replace myLineLayer and the field names with the real names.

select *, sum(dist) over (partition by grp order by id asc) as cumul_dist
from myLineLayer

enter image description here

3
  • 1
    The problem is that this is a small peace from a much bigger problem that i want to automate in a graphical model. That beeing said, it would be beneficial if the solution would be with the help of the field calculator functions. Commented Nov 20, 2023 at 14:53
  • and if I understand the solutin right it is just summing the segments and groups them. What I really want to achieve is: Assuming I have a line with 3 segments: Segment1 ( Value: 10 ) , Segment2 ( Value: 30 ), Segment3 ( Value: 5 ). The result would be Segment1 (Sum Value: 10), Segment2 ( Segment 1 + Segment 2: Sum Value: 10+30=40), Segment3 ( Segment 2 + Segment 3: Sum Value: 40+5=45). Commented Nov 20, 2023 at 14:59
  • that is what it is doing, i.e. the cumulative sum per group
    – JGH
    Commented Nov 20, 2023 at 15:12
6

Use this expression:

with_variable(
    'sedid',
    sed_id,
    array_sum(
        array_agg( 
            sum_in_kW, 
            group_by:=group, 
            filter:=sed_id<=@sedid
        )
    )
)

Red label shows the cumulative sum, calculated with the expression above: enter image description here

Not the answer you're looking for? Browse other questions tagged or ask your own question.