Group rows into sets of 5

后端 未结 2 429
慢半拍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.

    0 讨论(0)
  • 2020-12-06 21:50

    A bit of math can go a long way. subtracting 1 from all values puts the 5s (edge cases) into the previous group here, and 6's into the next. flooring the division by your group size and adding one give the result you're looking for. Also, the SQLFiddle example here fixes your iterative insert - the table only went up to 27.

    SELECT col1,
      floor((col1-1)/5)+1 as grpNum
    FROM tableA
    
    0 讨论(0)
提交回复
热议问题