This article is half-done without your Comment! *** Please share your thoughts via Comment ***
Check the below input data and expected output to start the range from 0 to first value and the first value to second value so on.
Input Data:
1 2 3 4 5 6 7 8 |
Val ----------- 108 116 226 308 416 426 |
Expected Data:
1 2 3 4 5 6 7 8 9 |
LowerRange UpperRange ----------- ----------- 0 108 108 116 116 226 226 308 308 416 416 426 426 NULL |
Create a table with sample data:
1 2 3 4 5 6 7 8 9 |
CREATE TABLE Ranges (Val INT) GO INSERT INTO Ranges(Val) VALUES (108),(116), (226),(308), (416),(426) |
Solution 1:
1 2 3 4 5 6 7 |
;with CTE as ( select *,row_number()over (order by Val) as rnk from (select 0 Val union select Val from Ranges) AS T ) select a.Val as LowerRange,b.Val as UpperRange from CTE a left outer join CTE b on a.rnk = b.rnk-1 |
Solution 2:
1 2 3 4 5 6 7 8 9 10 11 |
;WITH CTE AS ( SELECT Val , ROW_NUMBER() OVER (ORDER BY Val ASC) rnk FROM ( SELECT 0 Val UNION ALL SELECT Val from Ranges )a ) SELECT c.Val LowerRange , (SELECT TOP 1 Val FROM CTE c1 WHERE c1.rnk > c.rnk ) UpperRange FROM CTE c |
Please try the different solution for this puzzle and share it via comment...