有个表,见下:month 3月  4月 5月 6月
num  1     2   3   4现在我想获得比本身小的月份的叠加,如5月获得3月4月5月的叠加值,
就是应该得到
3月  4月 5月 6月
1     3   6   10
应该怎么实现?

解决方案 »

  1.   

    SELECT 
         month,
         3月3月,
         3月+4月 4月,
         3月+4月+5月 5月,
         3月+4月+5月+6月 6月
          
    FROM TB
         
       
      

  2.   

    select [month],
           3月,
           4月 = 3月 + 4月,
           5月 = 3月 + 4月 + 5月,
           6月 = 3月 + 4月 + 5月 + 6月\
    from tb
      

  3.   

    select [month], 
          3月, 
          4月 = 3月 + 4月, 
          5月 = 3月 + 4月 + 5月, 
          6月 = 3月 + 4月 + 5月 + 6月
    from tb 
      

  4.   

    楼上理解错了,3月4月是表的值,不是列名表的样式是这样的,只有2列,
    [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语句? 
      

  5.   


    select month,
    (select sum(num) from tb where month<=t.month ) as num
    from tb t
      

  6.   

    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 個資料列受到影響)
    */
      

  7.   

    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 行)
    */
      

  8.   

    select
     [month],
     (select sum(num) from tb where [month]<=t.[month] ) as num
    from
     tb t