Group rows into sets of 5

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

提交回复
热议问题