SELECT a.COL1, SUM(数量) 数量 FROM(
SELECT '1-4' AS COL1, 数量 FROM #T WHERE 号 >=1 AND 号 <=4
UNION ALL
SELECT '5-11' AS COL1, 数量 FROM #T WHERE 号 >4 AND 号 <=11
) AS a
GROUP BY a.COL1
--生成测试数据
--------------------------------
create table #T(号 int,数量 int)
insert into #T select 1 ,100
insert into #T select 2 ,100
insert into #T select 3 ,120
insert into #T select 4 ,60
insert into #T select 9 ,2000
insert into #T select 10,3000
insert into #T select 11,1000
--执行查询
-------------------------------------------------------------------------------------
select
号 = rtrim(e.号1)+'~'+rtrim(e.号2),
累计数量 = sum(f.数量)
from
(select 号1 = c.号,号2 = min(d.号)
from
(select a.号 from #t a where not exists(select 1 from #t where 号=a.号-1)) c,
(select b.号 from #t b where not exists(select 1 from #t where 号=b.号+1)) d
where c.号 < d.号
group by c.号) e,
#t f
where f.号 between e.号1 and e.号2
group by e.号1 ,e.号2
create table #T(号 int,数量 int)
insert into #T select 1 ,100
insert into #T select 2 ,100
insert into #T select 3 ,120
insert into #T select 4 ,60
insert into #T select 9 ,2000
insert into #T select 10,3000
insert into #T select 11,1000
select
号 = rtrim(e.id1)+'~'+rtrim(e.id1),
累计数量 = sum(f.数量)
from
(select
id1 = c.号,id2 = min(d.号)
from
(select
a.号
from
#t a
where
not exists(select 1 from #t where 号=a.号-1)) c ,
(select
a.号
from
#t a
where
not exists(select 1 from #t where 号=a.号+1)) d
where
c.号 < d.号
group by
c.号) e,
#t f
where
f.号 between e.id1 and e.id2
group by
e.id1 ,e.id2