BubbleKitty的小屋  
请不要拿技术眼光看菜鸟~~

今天我在CSDN里提的一個問題,非常感謝馬可老大~
-------------------------------------------------------------------------
测试数据
编号   物料类别    产品编号
1       铅笔        0001
2       铅笔        0002
3       铅笔        0001
4       钢笔        0004
5       钢笔        0005
6       钢笔        0004
7       圆珠笔      0007
8       圆珠笔      0008
9       圆珠笔      0007

等等

要求实现以下效果:
编号    物料类别   产品编号
1       铅笔       0001,0002
2       钢笔       0004,0005
3       圆珠笔     0007,0008

**我的目的是如果不重复则合并产品编号,如果重复则舍弃**

--------------------------------------
marco08(天道酬勤) ( ) 信誉:100    Blog  2007-1-9 15:23:01  得分: 20 

create table T(编号 int, 物料类别 nvarchar(10), 产品编号 char(5))
insert T select 1,       '铅笔',        '0001'
union all select 2,       '铅笔',        '0002'
union all select 3,       '铅笔',        '0001'
union all select 4,       '钢笔',        '0004'
union all select 5,       '钢笔',        '0005'
union all select 6,       '钢笔',        '0004'
union all select 7,       '圆珠笔',    '0007'
union all select 8,       '圆珠笔',      '0008'
union all select 9,       '圆珠笔',      '0007'

create function fun(@物料类别 nvarchar(10))
returns nvarchar(200)
as
begin
    
declare @re nvarchar(200)
    
set @re=''
    
select @re=@re+产品编号+',' from T where 物料类别=@物料类别 group by 产品编号

    
select @re=left(@relen(@re)-1)
    
return @re
end

select distinct 物料类别, dbo.fun(物料类别) from T

--result
物料类别                                    
---------- -------------------------------
钢笔         0004 ,0005 
铅笔         
0001 ,0002 
圆珠笔        
0007 ,0008 

(
3 row(s) affected)

后記:
核心語句中最后面的group by XXX 可舍棄重復。
select @re=@re+产品编号+',' from T where 物料类别=@物料类别 group by 产品编号

posted on 2007-01-09 17:19  BubbleKitty  阅读(5121)  评论(1)    收藏  举报