Tags

, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,


T-SQL Query | [ The Total Values Missing Puzzle ]

Puzzle Description

1. We have a table called FindGaps with a single column col1.
2. We have to find out how many total values are missing between starting values till the last value.
3. 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

TotalMissingValues
7

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
	,COl1 - row_number() OVER (ORDER BY COl1) rnk
FROM FindGaps
)
SELECT MAX(rnk) TotalMissingValues FROM CTE

--

Add a comment if you have any other solution in mind. We all need to learn. Keep Learning

Http://MSBISkills.com

Pawan Kumar Khowal