select month, (select sum(num) from tb where month<=t.month ) as num from tb t
if object_id('[tb]') is not null drop table [tb] go create table [tb] (month nvarchar(4),num int) insert into [tb] select N'3月',1 union all select N'4月',2 union all select N'5月',3 union all select N'6月',4select [month], (select sum(num)from tb where [month]<=t.[month])num from [tb]t /* month num ----- ----------- 3月 1 4月 3 5月 6 6月 10(4 個資料列受到影響) */
create table [tb] (month nvarchar(4),num int) insert into [tb] select N'3月',1 union all select N'4月',2 union all select N'5月',3 union all select N'6月',4select [month] , num = (select sum(num) from tb where [month] <= t.[month]) from tb tdrop table tb/* month num ----- ----------- 3月 1 4月 3 5月 6 6月 10(所影响的行数为 4 行) */不过建议楼主最好把月份<10的,月份前的0补上. create table [tb] (month nvarchar(5),num int) insert into [tb] select N'03月',1 union all select N'04月',2 union all select N'05月',3 union all select N'06月',4select [month] , num = (select sum(num) from tb where [month] <= t.[month]) from tb tdrop table tb/* month num ----- ----------- 03月 1 04月 3 05月 6 06月 10(所影响的行数为 4 行) */
select [month], (select sum(num) from tb where [month]<=t.[month] ) as num from tb t
month,
3月3月,
3月+4月 4月,
3月+4月+5月 5月,
3月+4月+5月+6月 6月
FROM TB
3月,
4月 = 3月 + 4月,
5月 = 3月 + 4月 + 5月,
6月 = 3月 + 4月 + 5月 + 6月\
from tb
3月,
4月 = 3月 + 4月,
5月 = 3月 + 4月 + 5月,
6月 = 3月 + 4月 + 5月 + 6月
from tb
[month] [nchar](10) NULL,
[num] [int] NULL表中的数据为
month num
3月 1
4月 2
5月 3
6月 4 现在我想获得这样的数据
month num
3月 1
4月 3
5月 6
6月 10应该怎么写sql语句?
select month,
(select sum(num) from tb where month<=t.month ) as num
from tb t
go
create table [tb] (month nvarchar(4),num int)
insert into [tb]
select N'3月',1 union all
select N'4月',2 union all
select N'5月',3 union all
select N'6月',4select [month],
(select sum(num)from tb where [month]<=t.[month])num
from [tb]t
/*
month num
----- -----------
3月 1
4月 3
5月 6
6月 10(4 個資料列受到影響)
*/
insert into [tb]
select N'3月',1 union all
select N'4月',2 union all
select N'5月',3 union all
select N'6月',4select [month] , num = (select sum(num) from tb where [month] <= t.[month]) from tb tdrop table tb/*
month num
----- -----------
3月 1
4月 3
5月 6
6月 10(所影响的行数为 4 行)
*/不过建议楼主最好把月份<10的,月份前的0补上.
create table [tb] (month nvarchar(5),num int)
insert into [tb]
select N'03月',1 union all
select N'04月',2 union all
select N'05月',3 union all
select N'06月',4select [month] , num = (select sum(num) from tb where [month] <= t.[month]) from tb tdrop table tb/*
month num
----- -----------
03月 1
04月 3
05月 6
06月 10(所影响的行数为 4 行)
*/
[month],
(select sum(num) from tb where [month]<=t.[month] ) as num
from
tb t