Here is the sample code
IF OBJECT_ID('dbo.Category','U') IS NOT NULL
DROP TABLE dbo.CategoryGO
CREATE TABLE Category
(
CategoryID INT
,CategoryValue INT
)
INSERT INTO Category(CategoryID, CategoryValue)
VALUES (1,1), (1,2), (1,4), (1,5), (2,8), (2,10), (3,11),(3,13)
--Get the next Category Value
;WITH CTEAS
(
SELECT CategoryID
,CategoryValue
,ROW_NUMBER() OVER(ORDER BY CategoryValue) AS Ranges
FROM dbo.Category
)
SELECT A.CategoryID
, A.CategoryValue
, B.CategoryValue AS NextCategoryValue
FROM
CTE A
LEFT JOIN CTE B
ON A.Ranges + 1 = B.Ranges
We can achieve the same functionality with LEAD() function with very less code and with a huge perf. improvement
--USE LEAD() Function to get next
category value
SELECT CategoryID,CategoryValue
,LEAD(CategoryValue) OVER(ORDER BY CategoryValue) AS NextCategoryValue
FROM dbo.Category
We can also use PARTITION BY in the OVER clause of lead function if we want to get the values based on categoryID or a key value. Here is the execution plan
This is very useful for date ranges and other stuff.
No comments:
Post a Comment