Chinaunix首页 | 论坛 | 博客
  • 博客访问: 197009
  • 博文数量: 7
  • 博客积分: 2010
  • 博客等级: 大尉
  • 技术积分: 600
  • 用 户 组: 普通用户
  • 注册时间: 2007-05-02 11:24
文章分类

全部博文(7)

文章存档

2008年(7)

我的朋友

分类: 数据库开发技术

2008-03-18 12:05:34

请问在SQL   2000中如何对某字段分组累加计算啊.比如我有下面的数据:  
    Field1           Field2              
    li                     20                  
    li                     30                    
    li                     10                    
    lu                     40                    
    lu                     20                    
   
  我想得到下面的累加字段Field3  
   
    Field1           Field2             Field3  
    li                     20                   20  
    li                     30                   50  
    li                     10                   60  
    lu                     40                   40  
    lu                     20                   60  
   
  请各位大侠指教! 
处理方法1:
select   identity(int,1,1)as   id,*   into   #temp   from   table  
  select   field1,field2,(select   sum(field2)   from   #temp   where   id<=a.id   and   field1=a.field1)   from   #temp   a 
处理方法2:
create   table   #t   (Field1   varchar(10)   ,         Field2   int)   
insert   into   #t   select          'li'              ,    20                   
insert   into   #t   select        'li'              ,   30                     
insert   into   #t   select          'li'              ,    10                     
insert   into   #t   select          'lu'              ,    40                     
insert   into   #t   select          'lu'              ,    20                     
    
select   identity(int,1,1)   as   tid   ,*     into   #temp   from   #t   
select     Field1   ,   Field2,   (select   sum(Field2)   from   #temp   where   Field1=A.field1   and   tid<=   A.tid   )   as   Field3  
    from   (select   *     from   #temp)   as   A  
    drop   table   #t,#temp
原文地址:
 
我在此基础上做了一点点改进:
create   table   #t2   (Field1 varchar(10), Field2 int,Field3 int)  
  insert   into   #t2   select               'li' ,20,50                  
  insert   into   #t2   select               'li' ,30,10                   
  insert   into   #t2   select               'li' ,10,70                 
  insert   into   #t2   select               'lu' ,40,20                    
  insert   into   #t2   select               'lu' ,20,30  
select * from  #t2
select * from #temp2
select   identity(int,1,1)   as   tid   ,*     into   #temp2   from   #t2  
  select     Field1,Field2,Field3,   (select   sum(Field3)-sum(Field2)  
from   #temp2   where     tid<=   A.tid   )   as   Field4  
    from   (select   *     from   #temp2)   as   A  
   
drop   table   #t,#temp
Field1=A.field1   and
阅读(899) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~