Answer the question
In order to leave comments, you need to log in
How to write a query in sql?
Good afternoon.
I have a table containing one (signed) integer field NUM. Each row
of this table contains a random number.
Each number appears in the table an arbitrary number of times.
It is necessary to find the maximum continuous (without missing numbers) range
presented in the table.
Thank you in advance.
Answer the question
In order to leave comments, you need to log in
This cannot be done with SQL alone without nested queries, since SQL does not allow you to get the value "before" and "after" the current record. Accordingly, there is no way to get their difference between them.
This has been discussed here https://stackoverflow.com/questions/3139323/findin...
set @lst := NULL;
set @grp := 0;
SELECT MAX(grp.cnt) AS max_range
FROM (
SELECT COUNT( rp.grp) AS cnt
FROM (
SELECT
MIN(r1.id) AS r1_id,
MIN(r1.num) AS r1_num,
MIN(r2.num) AS r2_num,
if ( r1.num > @lst + 1, @grp := @grp + 1, @grp) AS grp,
@lst := r1.num AS lst
FROM testing.integer_range as r1
JOIN testing.integer_range AS r2 ON r1.num = r2.num + 1 OR r1.num = r2.num - 1
GROUP BY r1.num
ORDER BY r1.num ASC
) AS rp
GROUP BY rp.grp
) AS grp;
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question