我试图编写一个SQL SELECT查询,该查询的批号列每5行递增一次,我尝试在动态行号上使用hacky整数除法,但是不能绕过第一批数字增量总是4行而不是5行(见图)。
RowNumber 1-5应为1,6-10应为2等。
我是如何实现这一目标的?
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
答案 0 :(得分:8)
这应该有效:
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
答案 1 :(得分:2)
试试这个:
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