SQL SELECT incremental batch number every X rows

前端 未结 2 2061
既然无缘
既然无缘 2021-02-04 21:02

I\'m trying to write a SQL SELECT query that has a batch number column that increments every 5 rows, I\'ve tried using a hacky integer division on a dynamic row number, but can\

相关标签:
2条回答
  • 2021-02-04 21:51

    Try this:

    SELECT  ROW_NUMBER() OVER (ORDER BY (SELECT 1)) AS RowNumber,
            CEILING(CAST(ROW_NUMBER() OVER (ORDER BY (SELECT 1)) AS DECIMAL(10,2))/5) AS BatchNo, *
    FROM    WorkQueue
    
    0 讨论(0)
  • 2021-02-04 22:03

    This should work:

    select ROW_NUMBER() OVER (Order by (select 0)) AS RowNumber,
    (case when convert(int, (ROW_NUMBER() OVER (Order by (select 0)) % 5))=0 then 0 else 1 end) + convert(int, (ROW_NUMBER() OVER (Order by (select 0)) / 5)) as BatchNumber,
    * from WorkQueue
    
    0 讨论(0)
提交回复
热议问题