2014-07-02 68 views
3

我正在嘗試編寫一個SQL SELECT查詢,它有一個每5行增加一個批號的列,我試過在動態行號上使用hacky整數除法,但可以不會繞過第一批次的增量,總是4行而不是5(見圖)。SQL SELECT增量批號每X行

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 

enter image description here

+2

減去1從你的第二個ROW_NUMBER使用。 1 + convert(int,((ROW_NUMBER()OVER(order by(select 0))-1)/ 5))as BatchNumber。 ROW_NUMBER從1開始計數,而不是零,這是問題的原因。當然是 –

+0

!謝謝,這很好! – andyno

回答

6

這應該工作:

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 
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