Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL SELECT incremental batch number every X rows

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't get around the first batch number increment always being 4 rows instead of 5 (see image).

RowNumber 1-5 should be 1, 6-10 should be 2 etc..

Any ideas how I can achieve this?

select * ROW_NUMBER() OVER (Order by (select 0)) AS RowNumber,
1 + convert(int, (ROW_NUMBER() OVER (Order by (select 0)) / 5)) as BatchNumber,
* from WorkQueue

enter image description here

like image 925
andyno Avatar asked Dec 12 '22 04:12

andyno


2 Answers

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
like image 68
st mnmn Avatar answered Dec 27 '22 18:12

st mnmn


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
like image 41
Jesuraja Avatar answered Dec 27 '22 20:12

Jesuraja