In SQLite, I have a table with 3 columns: id, value (integer), and sort_me. What I'm trying to query is groups of rows whose values are within +-50 range, and sort everything, within each group and across groups, by sort_me ascending. If a group consists of just one member, discard it.
Here is an example table:
id, value, sort_me
1, 1, 15
2, 102, 22
3, 3, 7
4, 101, 13
5, 312, 53
6, 6, 34
7, 309, 3
8, 104, 9
9, 521, 8
The expected result should be
7,5
3,1,6
8,4,2
So far I come up with
SELECT concat_ws(',', v1.id, group_concat(v2.id ORDER BY v2.sort_me ASC))
FROM t v1, t v2
WHERE v1.id < v2.id AND abs(v1.value - v2.value) < 50
GROUP BY v1.id
ORDER BY v1.sort_me ASC
Which yields
3,6
4,8
1,3,6
2,8,4
5,7
This is obviously wrong in multiple ways. First, beside the full groups, some sub-groups are also there. Second, the sorting inside group_concat() only affects v2 and v1 is always appears first. Third, the order across groups are also wrong because v1.sort_me may not be the smallest among each group.
I came up with a query myself. Not sure if a simpler solution exists.
Note: The
ORDER BYclause insidegroup_concat()is only supported since SQLite 3.44.0.