# Calculating cumulative line length on large dataset

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

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?

• Please explain how this method is "far too inefficient". What else have you tried?
– Erik
Oct 1, 2021 at 6:26
• 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 Oct 5, 2021 at 2:39
• @YogeshChavan need stored for future use Oct 5, 2021 at 2:40

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.

• 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. Oct 5, 2021 at 3:05
• @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