2015-02-06 98 views
-2

我有一個像下面SQLServer的查詢窗口化

select 1 group_rank, 1 row_rank union all 
select 1 , 2 union all 
select 1 , 3 union all 
select 1 , 4 union all 
select 1 , 5 union all 
select 2 , 1 union all 
select 2 , 2 union all 
select 2 , 3 union all 
select 2 , 4 union all 
select 2 , 5 union all 
select 3 , 1 union all 
select 3 , 2 union all 
select 3 , 3 union all 
select 3 , 4 union all 
select 3 , 5 union all 
select 4 , 1 union all 
select 4 , 2 union all 
select 4 , 3 union all 
select 4 , 4 union all 
select 4 , 5 

我想打破在大小row_rank還基於一個表。如果我的大小是2,則進一步拆分row_rank,如下所示。輸出第三列應該像下面

select 1 group_rank, 1 row_rank, 1 batch_number union all 
select 1 , 2, 1 union all 
select 1 , 3, 2 union all 
select 1 , 4, 2 union all 
select 1 , 5, 3 union all 
select 2 , 1, 4 union all 
select 2 , 2, 4 union all 
select 2 , 3, 5 union all 
select 2 , 4, 5 union all 
select 2 , 5, 6 union all 
select 3 , 1, 7 union all 
select 3 , 2, 7 union all 
select 3 , 3, 8 union all 
select 3 , 4, 8 union all 
select 3 , 5, 9 union all 
select 4 , 1, 10 union all 
select 4 , 2, 10 union all 
select 4 , 3, 11 union all 
select 4 , 4, 11 union all 
select 4 , 5, 12 

作爲分割大小是2,

前兩行與所述第一group_rank得到第一批次編號,

第三第四行與第一group_rank得到第二批數,

第五排在第1 group_rank得到第三批數量,

分前兩排在第二group_rank獲得第四批號,

第三第四行與第二group_rank得到5批號,

第五行與得到的第3 group_rank得到6批號

...等等。

因爲,我改變了拆分大小,,,批號應相應增長或縮小。 請提供我sql服務器TSQL查詢來做到這一點。

感謝,

+1

首先**您提供了**迄今爲止所做的工作 - 我們很樂意幫助您解決您的問題 - 但我們不僅僅提供所有類似的代碼.... 。 – 2015-02-06 06:15:47

回答

0

聽起來,簡單的數學對我來說,一點點從0基於1 /巫術至少:

((row_number() over (order by group_rank, row_rank) - 1)/@batch_size) + 1 

SQL Fiddle demo

這樣做是:

  • row_number() over (order by group_rank, row_rank):獲取整個集合中排序的行號,首先按0排序然後通過row_rank
  • - 1:通過「批量」鴻溝你想(在其最好的整數除法)
  • + 1:讓行號從0
  • 使結果1爲基礎,以匹配您的輸出
+0

感謝您提供快速回復。這非常有幫助。我採納了你的建議,只是修改得很少,以使其工作。 ((row_number()over(order by group_rank) - 1)/ @batch_size)+ 1 – user3558544 2015-02-06 06:50:08