lrary

时光荏苒,岁月流逝,仅以此纪念那一段走过来的开发岁月,希望哪天回首时,仍能想起一幕幕难忘的日子。

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

表Table1:  
  项目 金额  
  X1 100  
  X2 120  
  Y1   Y3 180  
  Y2 90  
  Z1 140  
  A1   A2   B1                   300  
  B2   Z2   C1                   150  
  要得到以下结果:  
  项目 金额  
  A 200  
  B 150  
  C 50  
  X 220  
  Y 270  
  Z 190  
  注:即头字母相同的累加,一个项目中如果有多于一个值则等分(如A1   A2   B1:300则A   200,B   100)。


解决方法:
create   table   Table1(项目   varchar(20),金额   int)   
  
insert   Table1   select   'X1'                         ,100   
  
union     all         select   'X2'                         ,120   
  
union     all         select   'Y1       Y3'               ,180   
  
union     all         select   'Y2'                         ,90   
  
union     all         select   'Z1'                         ,140   
  
union     all         select   'A1     A2       B1',300   
  
union     all         select   'B2       Z2   C1'         ,150   
  
go   
  
select * from table1
  
--查询处理   
    
  
--处理临时表   
  declare   @i   int   
  
select   @i=max(len(项目))   from   Table1   
  
set   rowcount   @i   
  
select   id=identity(int)   into   #t   from   syscolumns   a,syscolumns   b   
  
set   rowcount   0   
    
  
--统计出结果   
  select   项目,项目1=substring(a.项目,b.id,1),金额   
  
into   #t1   from   Table1   a,#t   b   
  
where   len(a.项目)>=b.id   and   patindex('   [^   ]%',substring('   '+a.项目,b.id,8000))=1   
    
  
select   项目=a.项目1,金额=sum(a.金额/b.cnt)     
  
from   #t1   a,(select   项目,cnt=count(*)   from   #t1   group   by   项目)b   
  
where   a.项目=b.项目   
  
group   by   a.项目1   
    
  
drop   table   #t,#t1   
  
go   
    
  
--删除测试   
  drop   table   Table1   
    
 


posted on 2006-05-13 14:42  lrary  阅读(313)  评论(0编辑  收藏  举报