- 爱易网页
 
                        - 
                            MSSQL教程
 
                        - 求一存储过程。帮忙顶一下。搞定就结贴。顶就有分。 
 
                         
                    
                    
                    日期:2014-05-18  浏览次数:20590 次 
                    
                        
                         求一存储过程。。各位大哥帮忙顶一下。搞定就结贴。。顶就有分。。
有这样一个表wsp 
 id         yg_id         wt_id                        dn 
 1                  1                     1                '一级,二级 ' 
 2                  1                     1                '二级 ' 
 3                  1                     1                '二级,三级 ' 
 4                  1                     2                'A ' 
 5                  1                     2                'B ' 
 6                  1                     2                'B,C ' 
 ... 
 ... 
 我想用一个存储过程,通过输入参数yg_id和wt_id查出这样一个结果 
 yg_id            wt_id                                          PS 
 1                              1                   '一级   1   二级   3   三级   1 ' 
 1                              2                   'A      1      B      2      C      1 ' 
 也就是相当于把所有yg_id和wt_id相同的dn统计出来。。 
 请牛人指点一二。谢谢了`
------解决方案--------------------
把所有符合条件的记录的dn拆分放到临时表中,按yg_id和wt_id分组,分别统计出dn中每个元素的个数连接到一起。
------解决方案--------------------
create table test(id int,yg_id int,wt_id int,dn varchar(20)) 
 insert test select 1,1,1, '一级,二级 ' 
 union all select 2,1,1, '二级 ' 
 union all select 3,1,1, '二级,三级 ' 
 union all select 4,1,2, 'A ' 
 union all select 5,1,2, 'B ' 
 union all select 6,1,2, 'B,C ' 
 go 
  
 create proc prc 
 as 
 begin 
 	select top 200 bh=identity(int,1,1) into # from syscolumns a,syscolumns b 
 	select yg_id,wt_id,dn=substring(a.dn,b.bh,charindex( ', ',a.dn+ ', ',b.bh)-b.bh) from test a,# b 
 	where b.bh <=len(a.dn) 
 	and charindex( ', ', ', '+a.dn,b.bh)=b.bh 
 	drop table # 
 end 
 go 
  
 create function dbo.fn_Merge(@wtid varchar(100)) 
 returns varchar(8000) 
 as 
 begin 
    declare @name varchar(8000) 
    set @name= ' ' 
    select @name=@name+ '  '+dn+ '  '+rtrim(cnt) from tmp2 where wt_id=@wtid 
    return stuff(@name,1,1, ' ') 
 end 
 go 
  
 create table tmp(yg_id int,wt_id int,dn varchar(20)) 
 insert tmp exec prc  
  
 select * into tmp2 from 
 ( 
 	select yg_id,wt_id,dn,cnt=count(*) from tmp 
 	group by yg_id,wt_id,dn 
 )a 
  
 select distinct yg_id,wt_id,PS=dbo.fn_Merge(wt_id) from 
 ( 
 	select yg_id,wt_id,dn,cnt=count(*) from tmp2 
 	group by yg_id,wt_id,dn 
 )a 
  
 drop table test 
 drop table tmp,tmp2 
 drop proc prc 
 drop function fn_Merge 
  
  
 yg_id       wt_id       PS      
 ----------- ----------- ---------------------- 
 1           1           二级 3 三级 1 一级 1 
 1           2           A 1 B 2 C 1 
  
 (所影响的行数为 2 行)
                         球一个SQL语句:自动给养其他月份为0