Group rows into sets of 5

后端 未结 2 437
慢半拍i
慢半拍i 2020-12-06 21:02

TableA

Col1
----------
1
2
3
4....all the way to 27

I want to add a second column that assigns a number to groups of 5.

Results

2条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-06 21:44

    You can use this:

    ;WITH CTE AS
    (
        SELECT col1,
               RN = ROW_NUMBER() OVER(ORDER BY col1)
        FROM TableA
    )
    SELECT col1, (RN-1)/5+1 col2
    FROM CTE;
    

    In your sample data, col1 is a correlative without gaps, so you could use it directly (if it's an INT) without using ROW_NUMBER(). But in the case that it isn't, then this answer works too. Here is the modified sqlfiddle.

提交回复
热议问题