concept island problem in category sql

appears as: islds problems, islds problem, islds problem
SQL Server MVP Deep Dives

This is an excerpt from Manning's book SQL Server MVP Deep Dives.

This chapter describes problems known as gaps and islands and their solutions. I start out with a description of gaps and islands problems, describe the common variations on the problems, and provide sample data and desired results. Then I move on to ways of handling gaps and islands problems, covering multiple solutions to each problem and discussing both their logic and performance. The chapter concludes with a summary of the solutions.

Table 4. Desired result for variation on the islands problem

mn

mx

val

2

5

A

7

11

B

13

19

A

23

29

C

31

43

A

47

59

C

This is a variation on the islands problem. Listing 12 shows the solution to this problem.

Listing 12. Solution to variation on the islands problem
WITH C AS ( SELECT id, val, ROW_NUMBER() OVER(ORDER BY id) - ROW_NUMBER() OVER(ORDER BY val, id) AS grp FROM dbo.T1 ) SELECT MIN(id) AS mn, MAX(id) AS mx, val FROM C GROUP BY val, grp ORDER BY mn;