# Using RECURSIVE in Virtual Layer

I don't think you need recursive, it looks like you want subtotals for different categories of "DIST_KM"

Does this give something close to want you expect:

SELECT COUNT(*) as anzahl, SUM(FLUX) AS summe,
ROUND(DIST_KM +0.5, 0) AS Dist_group
FROM "flows_workday_GK5"
GROUP BY ROUND(DIST_KM +0.5, 0)


Edit:
There will be gaps in the groups if the data is sparse and not all distance intervals are represented in the data.
If you would prefer bigger intervals as the distances increase you could try this query:

SELECT COUNT(*) as anzahl, SUM(FLUX) AS summe,
CAST(DIST_KM AS INTEGER) || '-' || CAST(DIST_KM + 1 AS INTEGER) AS Dist_group
FROM "flows_workday_GK5"
GROUP BY CAST(DIST_KM AS INTEGER)
WHERE DIST_KM < 10
UNION
SELECT COUNT(*) as anzahl, SUM(FLUX) AS summe,
CAST(CAST(GIS_Length/2  AS INTEGER)*2 AS VARCHAR(4)) || '-' || CAST(CAST(GIS_Length/2 + 1 AS INTEGER)*2 AS VARCHAR(4)) AS Dist_group
FROM "flows_workday_GK5"
GROUP BY CAST(DIST_KM/2 AS INTEGER)
WHERE DIST_KM >=10 AND DIST_KM < 20
UNION
SELECT COUNT(*) as anzahl, SUM(FLUX) AS summe,
CAST(CAST(GIS_Length/10  AS INTEGER)*10 AS VARCHAR(4)) || '-' || CAST(CAST(GIS_Length/10 + 1 AS INTEGER)*10 AS VARCHAR(4)) AS Dist_group
FROM "flows_workday_GK5"
GROUP BY CAST(DIST_KM/10 AS INTEGER)
WHERE DIST_KM >=20


This will give 1km groupings from 0 to 10km, 2km groups from 10 to 20 and 10km intervals for distances greater than or equal to 20.

With RECURSIVE query, you have to do a generate_series (PostgreSQL function not supported by SQLite), which create you a number series from conf.start to conf.stop by conf.step.

Then, retrieve this number and do what you want with, here your flow's summation SELECT.

Here the Virtual Layers / SQLite / GeoPackage working code :

-- number series
WITH RECURSIVE generate_series(category) AS (
SELECT conf.start
FROM conf
UNION ALL
SELECT category + conf.step
FROM generate_series, conf
WHERE category + conf.step <= conf.stop
),

-- configuration
conf AS (
SELECT
1 AS start,
5 AS stop,
1 AS step
)

-- query
SELECT gs.category, COUNT(*) AS anzahl, SUM(f.FLUX) AS summe
FROM flows AS f, generate_series gs, conf
WHERE f.DIST_KM >= category
AND DIST_KM < category + conf.step
GROUP BY gs.category


EDIT

You can make the couple queries generate_series and conf more independent :

-- number series
WITH RECURSIVE generate_series(category, upper_category) AS (
SELECT conf.start,
conf.start + conf.step
FROM conf
UNION ALL
SELECT category + conf.step,
upper_category + conf.step
FROM generate_series, conf
WHERE category + conf.step <= conf.stop
),

-- configuration
conf AS (
SELECT
1 AS start,
5 AS stop,
1 AS step
)

-- query
SELECT gs.category, COUNT(*) AS anzahl, SUM(f.FLUX) AS summe
FROM flows AS f, generate_series gs
WHERE f.DIST_KM >= category
AND DIST_KM < upper_category
GROUP BY gs.category