SQL语句特---殊统计(1)

本文介绍了一种使用SQL处理复杂表格数据的方法,通过创建临时表并对数据进行合理的分组和统计,实现了对包含多个项目的金额数据的高效处理。

表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)。


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


转载于:https://www.cnblogs.com/lrary/archive/2006/05/13/399150.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值