2016-08-19 19 views
0

你好發展共同體差距基於分區,如何分配數字到一組行對連續的數字SQL

是否有號碼指定給一組行的方式劃分基於在領域的空白SQL中的連續數字?我一直在尋找/嘗試各種各樣的東西來爲這個問題做出幾天的回答,並且已經空了。請看例子:

CREATE TABLE #example 
(ID int, Service_Date date, Item_Num int, Desired_Column int) 

INSERT INTO #example VALUES 
('1111', GetDate(), 4, 1), 
('1111', GetDate(), 5, 1), 
('1111', GetDate(), 7, 2), 
('1111', GetDate(), 8, 2), 
('1111', GetDate(), 9, 2), 
('1111', GetDate(), 11, 3), 
('1111', GetDate(), 12, 3), 
('1111', GetDate(), 13, 3) 

我想分配Desired_Column中的值,但是失敗。每次在連續的Item_Num值中出現間隙時,應分配一個新號碼。我已經嘗試了使用DENSE_RANK(),PARTITION BY,NTILE(),找到第一個/下一個行項目號之間的差異的多種方法,但我無法實現這個工作。這甚至有可能嗎?

感謝您抽出時間,很感激。

+1

什麼是您的DBMS? – dnoeth

+0

谷歌「SQL差距和島嶼」的問題,你會發現你可能想要的所有例子。 –

+0

可能的重複[如何找到與SQL運行計數器的「差距」?](http://stackoverflow.com/questions/1312101/how-do-i-find-a-gap-in-running-counter -with-sql) –

回答

1

這是一個間隙&島問題,一個常見的解決方案應用嵌套的解析函數。首先,根據條件計算一個標誌(這裏:當前行與前一行之間的間隔大於1),然後對該標誌執行累積和:

with cte as 
(

    select ..., 
     case when lag(Item_Num) over (partition by ID order by Item_Num) + 1 
       = Item_Num 
      then 0 -- gap = 1 -> part of the previous group 
      else 1 -- gap > 1 ->new group 
     end as flag 
    from #example 
) 
select ..., 
    sum(flag) over (partition by ID order by Item_Num) 
from cte 
相關問題