2015-10-15 65 views
1

我有整數值:(199903,199908,201203,201408,201410,201501,201503) 和我想通過的範圍爲3SQL分組整數由範圍

內的整數組這些整數在這個例子中,分組將是以下幾點:

199903 (group 1) 
199908 (group 2) 
201203 (group 3) 
201408 (group 4) 
201410 (group 4) 
201501 (group 5) 
201503 (group 5) 
+0

如果你有201505會發生什麼?是第5組的一部分還是第6組? – zimdanen

+0

@zimdanen它會讓組6 – decompiled

回答

2

您可以使用窗口函數DENSE_RANK

LiveDemo

CREATE TABLE #mytable(val INTEGER); 

INSERT INTO #mytable(val) 
VALUES(199903),(199908),(201203),(201408),(201410),(201501),(201503); 

SELECT 
    val, 
    [group] = DENSE_RANK() OVER (ORDER BY val/3) 
FROM #mytable; 

輸出:

╔════════╦═══════╗ 
║ val ║ group ║ 
╠════════╬═══════╣ 
║ 199903 ║  1 ║ 
║ 199908 ║  2 ║ 
║ 201203 ║  3 ║ 
║ 201408 ║  4 ║ 
║ 201410 ║  4 ║ 
║ 201501 ║  5 ║ 
║ 201503 ║  5 ║ 
╚════════╩═══════╝ 
+1

謝謝!我不得不使用val/4,但這很好用! – decompiled

+0

@decompiled不客氣:) – lad2025

0

我懷疑你的意思是由三個或更少的不同的序列。因此,當差異大於3時,會開始一個新時期。在SQL Server 2012+中,您可以使用lag()。在SQL Server 2008中,這裏有一種方法:

with t as (
     select t.*, 
      (case when t.val - tprev.val < 3 then 0 else 1 end) as IsGroupStart 
     from table t outer apply 
      (select top 1 t2.val 
      from table t2 
      where t2.val < t.val 
      order by t2.val desc 
      ) tprev 
    ) t 
select t.val, t2.grp 
from t outer apply 
    (select sum(IsGroupStart) as grp 
     from t t2 
     where t2.val <= t.val 
    ) t2;