SQL按范围分组整数
我有整数值:199903、199908、201203、201408、201410、201501、201503 我想把这些整数按3范围内的整数分组 在本例中,分组如下:SQL按范围分组整数,sql,sql-server,sql-server-2008-r2,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) 您可以使用窗口函数密集排列: 输出: ╔════════╦═══════╗ ║ val
199903 (group 1)
199908 (group 2)
201203 (group 3)
201408 (group 4)
201410 (group 4)
201501 (group 5)
201503 (group 5)
您可以使用窗口函数密集排列: 输出:
╔════════╦═══════╗
║ val ║ group ║
╠════════╬═══════╣
║ 199903 ║ 1 ║
║ 199908 ║ 2 ║
║ 201203 ║ 3 ║
║ 201408 ║ 4 ║
║ 201410 ║ 4 ║
║ 201501 ║ 5 ║
║ 201503 ║ 5 ║
╚════════╩═══════╝
我猜你指的是相差三倍或更少的序列。因此,当差值大于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;
如果您有201505,会发生什么?那是第五组还是第六组?@zimdanen这会让第六组谢谢你!我必须使用val/4,但这非常有效!
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;