I have a line split into segments that I want to calculate the accumulative length for, like this:

enter image description here

I can achieve this easily on a smaller dataset with this inbuilt function in the field calculator in QGIS:

aggregate('layer', 'sum', "Length", "id"<=attribute(@parent, 'id'))

However, my dataset has hundreds of thousands of lines and this method is far too inefficient.

Is there a more effective way to achieve this?

  • 2
    Please explain how this method is "far too inefficient". What else have you tried?
    – Erik
    Oct 1, 2021 at 6:26
  • 1
    Hello @JUNGLE, how are you expecting the results, on the fly or stored somewhere for further use:) Oct 1, 2021 at 8:06
  • @Erik inefficient as it took over 3 days to process just 1 line network out of about a dozen I need to do
    – JUNGLE
    Oct 5, 2021 at 2:39
  • @YogeshChavan need stored for future use
    – JUNGLE
    Oct 5, 2021 at 2:40

1 Answer 1


For a large amount of lines, you may have better efficiency by using a database and running this computation directly in the DB.

Here is a solution using a virtual layer. Go the the menu layer / add layer / add-edit virtual layer and enter the following query.

select *, 
   sum("length") over (order by id) as cumul, 
   sum("length") over (partition by gp order by id) as cumul_by_group
from myLayer

The 1st computation returns the total cumulative length, while the 2nd one groups them (by connected segments maybe?), it's up to you to choose which one to use.

enter image description here

  • That works good thanks. Would it be easy to adjust it slightly to get the cumulative length of the start point and cumulative length of the endpoint? In your example, “cumal” is the cumulative length of the endpoint. The cumulative length of the start point would equal the cumulative length of the endpoint of the previous line segment.
    – JUNGLE
    Oct 5, 2021 at 3:05
  • 1
    @JUNGLE sure, just remove the current segment length: sum("length") over (order by id) - "length" as cumul_start
    – JGH
    Oct 5, 2021 at 12:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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