SQL按范围分组整数

时间:2015-10-15 20:44:50

标签: sql sql-server sql-server-2008-r2

我有整数值:(199903,199908,201203,201408,201410,201501,201503) 我想用整数落在3的范围内对这些整数进行分组。

在此示例中,分组如下:

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

2 个答案:

答案 0 :(得分: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 :(得分: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;