第一张表中的数据:    
      1  1000 
      2  2000 
      3  3000 
      4  4000 
      5  5000 第二张表中的数据: 
      1  1000 
      2  3000 
      3  6000 
      4  10000 
      5  15000 第二张表中的数据,是第一张表中前几列数据之和,比如说:第二张表中的第3行数据为6000,是由第一张表中前3列1000+2000+3000,这三个数相加之和,问:这种情况如何用SQL语句实现,请各位大侠指点

解决方案 »

  1.   

    -- =========================================
    -- -----------t_mac 小编-------------
       ---希望有天成为大虾---- 
    -- =========================================IF OBJECT_ID('tb') IS NOT NULL
      DROP TABLE tb
    GO
    CREATE TABLE tb(id int ,num int )
    go
    insert tb SELECT 
    1,  1000 UNION ALL SELECT
          2 , 2000 UNION ALL SELECT
          3 , 3000 UNION ALL SELECT
          4 , 4000 UNION ALL SELECT
          5 , 5000 
    go
    select *,SUMa=(SElect SUM(num) from tb where id<=t.id)
    from tb tgo
    /*------------
    id          num         SUMa
    ----------- ----------- -----------
    1           1000        1000
    2           2000        3000
    3           3000        6000
    4           4000        10000
    5           5000        15000(5 行受影响)
    -------*/
      

  2.   

    DECLARE @TB TABLE([ID] INT, [COL] INT)
    INSERT @TB 
    SELECT 1, 1000 UNION ALL 
    SELECT 2, 2000 UNION ALL 
    SELECT 3, 3000 UNION ALL 
    SELECT 4, 4000 UNION ALL 
    SELECT 5, 5000SELECT ID,(SELECT SUM(COL) FROM @TB WHERE ID<=T.ID) AS COL
    FROM @TB AS T
    /*
    ID          COL         
    ----------- ----------- 
    1           1000
    2           3000
    3           6000
    4           10000
    5           15000
    */
      

  3.   

    create  table tb(id int, b int )
    insert into tb select 1,  1000 
    union all select      2,  2000 
    union all select      3,  3000 
    union all select      4,  4000 
    union all select      5, 5000 
    select id,b=(select sum(b) from tb where id<=t.id ) from tb t
    /*id          b
    ----------- -----------
    1           1000
    2           3000
    3           6000
    4           10000
    5           15000(5 行受影响)*/
      

  4.   

    来个不一样的
    select sum(a.b) from tb a inner join tb b on  
     a.id <= b.id group by (b.id)----------- 
    1000
    3000
    6000
    10000
    15000
      

  5.   

    create  table tb(id int, b int )
    insert into tb select 1,  1000 
    union all select      2,  2000 
    union all select      3,  3000 
    union all select      4,  4000 
    union all select      5, 5000  --
    select id,b=(select sum(b) from tb where id<=t.id) from tb t