表T1:
  日期         品种         产量        月份
 2007-04-04    JC10         20           4
 2007-04-04    T/C20        30           4
 2007-04-04    T/C20        40           4
 2007-04-05    JC10         10           4
 2007-04-06    JC10         15           4如何根据表T1得到表T2:
  日期         品种        产量          本月累计
  2007-04-04   JC10        20              20
  2007-04-04   T/C20       30              30
  2007-04-04   T/C20       40              70
  2007-04-05   JC10        10              30
  2007-04-06   JC10        15              45

解决方案 »

  1.   

    --增加唯一ID字段create table #t(id int identity(1,1),日期 datetime, 品种 varchar(100), 产量 int, 月份 int)insert into #t
    select '2007-04-04','JC10',20,4 union all
    select '2007-04-04','T/C20',30,4 union all
    select '2007-04-04','T/C20',40,4 union all
    select '2007-04-05','JC10',10,4 union all
    select '2007-04-06','JC10',15,4
    select 日期,品种,产量,(select sum(产量) from #t where 品种=A.品种 and 日期<=A.日期 and ID<=A.ID) as 本月累计
    from #t as Adrop table #t
      

  2.   

    --先改个数据,同天同品种有点问题.if object_id('pubs..tb') is not null
       drop table tb
    gocreate table tb(日期 varchar(10),品种 varchar(10),产量 int)
    insert into tb(日期,品种,产量) values('2007-04-04',    'JC10' ,        20)
    insert into tb(日期,品种,产量) values('2007-04-04',    'T/C20',        30)
    insert into tb(日期,品种,产量) values('2007-04-05',    'T/C20',        40)
    insert into tb(日期,品种,产量) values('2007-04-05',    'JC10' ,        10)
    insert into tb(日期,品种,产量) values('2007-04-06',    'JC10' ,        15)
    goselect *,(select sum(产量) from tb where 日期<=b.日期 and 品种 = b.品种) as '本月累计' from tb bdrop table tb/*
    日期         品种         产量          本月累计        
    ---------- ---------- ----------- ----------- 
    2007-04-04 JC10       20          20
    2007-04-04 T/C20      30          30
    2007-04-05 T/C20      40          70
    2007-04-05 JC10       10          30
    2007-04-06 JC10       15          45(所影响的行数为 5 行)
    */
      

  3.   

    楼主要得到的结果,应该总结来说,使用
    t1表和自身通过不对等关联,然后,再使用group by 汇总就好了。