P
P
Proshka172018-11-23 01:15:21
MySQL
Proshka17, 2018-11-23 01:15:21

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

3 answer(s)
A
atawerrus, 2018-11-23
@atawerrus

select max(field) as max_field from table_name

Y
Yordi, 2018-11-24
@Oleg_Yozhik

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...

P
Pavel Bezrukov, 2018-11-24
@bezrukovPS

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 question

Ask a Question

731 491 924 answers to any question