Tags
Complex SQL Challenges, complex sql statement(puzzle), Complex TSQL Challenge, Divide rows into two columns, Interesting Interview Questions, Interview Qs.SQL SERVER Questions, Interview questions on Joins, Interview Questions on SQL, InterviewQuestions, InterviewQuestions for SQL, Joins, Joins Interview questions, Joins Puzzle, Khowal, last non null puzzle, Learn complex SQL, Learn SQL, Learn T-SQL, Objective Puzzle, Pawan, Pawan Khowal, Pawan Kumar, Pawan Kumar Khowal, PL/SQL Challenges, Prev Value puzzle, Previous value puzzle, puzzle sql developer, Puzzles, Queries for SQL Interview, SELECT Puzzle, SQL, SQL 2012, SQL 2014, SQL 2014 Interview Questions, SQL Challenge, SQL Challenges, SQL Interview Questions, SQL Joins, SQL pl/sql puzzles, SQL Puzzles, SQL Queries, SQL Quiz, SQL Server Database, SQL SERVER Interview questions, SQL Skills, SQL Sudoku, SQL Top clause, SQL Trikcy question, sql/database interview for puzzle sql developer, SQLSERVER, T SQL Puzzles, T-SQL Challenge, T-SQL Query | [ The Complex Week Puzzle ], The Biggest Gap Puzzle, The Gap Puzzle, The Gap Puzzle Puzzle, The Tree Puzzle, TOP Clause, Tough SQL Challenges, Tough SQL Puzzles, Tricky Questions, TSQL, TSQL Challenge, TSQL Challenges, TSQL Interview questions, TSQL Queries, Week puzzle
T-SQL Query | [ The Gap Puzzle – III ]
Puzzle Description
1. We have a table called FindGaps with a single column col1.
2. If we have gap of more than 2 then we will conside that as a GAP.
3. We have to find out the gaps between these numbers in two columns like when the Gap starts and when the gap ends.
4. Please check out the sample input and expected output for details
Sample Input
Col1 |
1 |
3 |
4 |
5 |
6 |
7 |
9 |
11 |
15 |
17 |
Expected Output
RangeStart | RangeEnd |
1 | 11 |
15 | 17 |
Rules/Restrictions
- The solution should be should use “SELECT” statement or “CTE”.
- Add your solution(s) in the comments section or send you solution(s) to pawankkmr@gmail.com
Script
Use the below script to generate the source table and fill them up with the sample data.
-- CREATE TABLE FindGaps ( Col1 INT ) GO INSERT INTO FindGaps(Col1) VALUES (1),(3),(4),(5),(6),(7),(9),(11),(15),(17) CREATE CLUSTERED INDEX Ix_Gaps ON FindGaps(Col1) --
Update June 16 | Solution1 – Pawan Kumar Khowal
-- ;WITH CTE AS ( SELECT COl1 ,CASE WHEN COl1 - lag(col1) OVER (ORDER BY COl1) <= 2 THEN 0 ELSE 1 END rnk FROM FindGaps ) ,CTE2 AS ( SELECT COl1,SUM(rnk) OVER (ORDER BY Col1 rows unbounded preceding) grouper FROM CTE ) SELECT MIN(col1) RangeStart , MAX(col1) RangeEnd FROM CTE2 GROUP BY grouper --
Add a comment if you have any other solution in mind. We all need to learn. Keep Learning
Http://MSBISkills.com
Pawan Kumar Khowal