22,209
社区成员
发帖
与我相关
我的任务
分享
create table tb(身高 varchar(10),人数 int)
insert into tb select '190-199',2
insert into tb select '180-189',5
insert into tb select '170-179',15
insert into tb select '160-169',22
insert into tb select '150-159',16
insert into tb select '140-149',2
go
select 身高,人数,(select SUM(人数) from tb where 身高>=a.身高) 累计人数
from tb a
/*
身高 人数 累计人数
---------- ----------- -----------
190-199 2 2
180-189 5 7
170-179 15 22
160-169 22 44
150-159 16 60
140-149 2 62
(6 行受影响)
*/
go
drop table tb
---2000
select id=identity(int,1,1),* into #t from tb
select 身高,人数,(select sum(人数) from #t where id<=t.id) from #t t
use Tempdb
go
--> -->
declare @T table([身高] nvarchar(7),[人数] int)
Insert @T
select N'190-199',2 union all
select N'180-189',5 union all
select N'170-179',15 union all
select N'160-169',22 union all
select N'150-159',16 union all
select N'140-149',2
;WITH a
AS
(
Select * ,ROW_NUMBER()OVER(ORDER BY (SELECT 1)) AS row
from @T
)
SELECT [身高],[人数], (SELECT SUM([人数]) FROM a WHERE row<=t.row)
from a AS t
/*
身高 人数 (沒有資料行名稱)
190-199 2 2
180-189 5 7
170-179 15 22
160-169 22 44
150-159 16 60
140-149 2 62*/