SQL SERVER number segment Merging

Source: Internet
Author: User
Code: create table # TMP (
Id int,
S nvarchar (100 ),
E nvarchar (100 ))
 
Insert into # TMP (ID, S, E)
SELECT 2000, UNION ALL
SELECT 4000, UNION ALL
SELECT 6000, UNION ALL
SELECT 30000, UNION ALL
SELECT 50000, UNION ALL
SELECT 40000

SELECT max (a. id) id, a. s, min (case when (B. e is not null) THEN B. e ELSE a. e end) FROM # tmp
Left JOIN # tmp B ON a. id = B. id AND a. e + 1 = B. s
Where not exists (SELECT 1 FROM # tmp WHERE e + 1 = a. s AND id = a. id)
And not exists (SELECT 1 FROM # tmp WHERE s + 1 = B. e AND id = a. id)
Group by a. id, a. s order by id

Result <p> id s e
1 4000
1 5000 6000
2 20001 40000 </p> <p> (3 rows affected)
</P>

Url: http://greatverve.cnblogs.com/archive/2011/07/22/sql-Merge.html

Related Article

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.