Question

I need to increment +1 every 4 records over a table column, I've tried to use ROW_NUM() but my dirty workaround does not make sense.

This is what I need:

Index PeriodID
1       1
1       2
1       3
1       4
2       5
2       6
2       7
2       8

PeriodID is the primary key (clustered index) for table "Periods", I've heard about window functions LAG() and LEAD() but not sure if I can apply the concept for this scenario, the following syntax is my failed dirty trick attempt:

select row_number() over (order by periodid)/4+1, periodid from periods

Result I get:

Index PeriodID
1       1
1       2
1       3
2       4
2       5
2       6
2       7
3       8

I understand why I'm getting this result but I would like to know if there is a built in T-SQL function that can help to achieve what I need.

Any thoughts, suggestions are welcome

Thanks

Was it helpful?

Solution

I am not that familiar with built-ins to solve this kind of problem, but you can do it with plain math (and I'm sure someone could tighten this up, just a first pass):

CREATE TABLE #t (PeriodID int PRIMARY KEY, ExpectedIndex int);
INSERT INTO #t VALUES (1, 1),(2, 1),(3, 1),(4, 1),(5, 2),(6, 2),(7, 2),(8, 2),(9, 3),(10, 3),(11, 3),(13, 3);

SELECT ((RowNum - ((RowNum - 1) % 4)) / 4) + 1 AS [Index], ExpectedIndex, PeriodID
FROM (
    SELECT ROW_NUMBER() OVER (ORDER BY PeriodID) AS RowNum, ExpectedIndex, PeriodID FROM #t
    ) AS tSub1

DROP TABLE #t;

EDIT: I was curious, here's a LAG version (again, no doubt not optimized), plus subqueried out just to Show My Work:

SELECT
    (RowNum - IncrementalLag) / 4 AS ZeroBasedIndex
    ,((RowNum - IncrementalLag) / 4) + 1 AS [Index]
    ,ExpectedIndex
    ,PeriodID
FROM
    (
    SELECT 
        RowNum
        ,LAG(RowNum,1,0) OVER (ORDER BY RowNum) % 4 AS IncrementalLag
        ,ExpectedIndex
        ,PeriodID
    FROM (
        SELECT ROW_NUMBER() OVER (ORDER BY PeriodID) AS RowNum, ExpectedIndex, PeriodID FROM #t
        ) AS tSub1
    ) AS tSub2;

OTHER TIPS

I believe @downwitch is right, is a simple math problem, however I believe I become with a possible answer:

select (row_number() over (order by primaryKeyColumnName) -1)/N from table

where N is the number of records to create a new partition

Hope this answer is valid for other people too

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top