Number range Problems

Source: Internet
Author: User

First, the basic data is as follows:

Use tempdb;
Go
If object_id ('dbo. t1') is not null
Drop table DBO. T1
Go
Create Table DBO. T1 (col1 int not null primary key );
Insert into DBO. T1 (col1) values (1 );
Insert into DBO. T1 (col1) values (2 );
Insert into DBO. T1 (col1) values (3 );
Insert into DBO. T1 (col1) values (100 );
Insert into DBO. T1 (col1) values (101 );
Insert into DBO. T1 (col1) values (103 );
Insert into DBO. T1 (col1) values (104 );
Insert into DBO. T1 (col1) values (105 );
Insert into DBO. T1 (col1) values (106 );

 

Problem 1: locate the range of missing numbers. If the range is the same as the data above, the returned value is
4 ~ 99 102 ~ 102


One method:
Select col1 + 1 as start_range,
(Select Min (col1) from DBO. T1 as B
Where B. col1> A. col1)-1 as end_range
From DBO. T1 as
Where not exists
(Select * From DBO. T1 as B
Where B. col1 = A. col1 + 1)
And col1 <(select max (col1) from DBO. T1 );

 

Easier to understand:
Select cur + 1 as start_range, NXT-1 as end_range
From (select col1 as cur,
(Select Min (col1) from DBO. T1 as B
Where B. col1> A. col1) as NXT
From DBO. T1 as a) as d
Where NXT-cur> 1;

 

Question 2: locate all gaps (all missing numbers)
Select n
From DBO. Nums
Where n between (select Min (col1) from DBO. T1)
And (select max (col1) from DBO. T1)
And not exists (select * From DBO. T1 where col1 = N );

 

Problem 3: Find the existing range
Select min (col1) as start_range, max (col1) as end_range
From (select col1,
(Select Min (col1) from DBO. T1 as B
Where B. col1> = A. col1
And not exists
(Select * From DBO. T1 as C
Where B. col1 = C. col1-1) as GRP
From DBO. T1 as a) as d
Group by GRP;

 

Simple Method:
Select min (col1) as start_range, max (col1) as end_range
From (select col1, col1-row_number () over (order by col1) as GRP
From DBO. T1) as d
Group by GRP;

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.