SQL中如何按照条件合并多行的数据

来源:百度知道 编辑:UC知道 时间:2024/06/18 09:28:19
例如:
合并前:
701000451 300000214 R4 R6 R7 R12 R148
701000451 300000214 (R3-C12)
701000682 303000053 C421 C427 C429
701000682 303000053 C1 C4 C5
701000753 301000152 C115 C118 C121
701000753 301000152 C225 C228
701000753 301000152 C236 C237

合并后效果:
701000451 300000214 R4 R6 R7 R12 R148(R3-C12)
701000682 303000053 C421 C427 C429 C1 C4 C5
701000753 301000152 C115 C118 C121 C225 C228 C236 C237

用什么语句可以做到这种效果啊,请高手指教
查询到的结果是使用以下语句查询的
select code,ccode,loc from bomloc where opid in (select opid from bomloc group by opid having count(opid)>1)
查询出来的结果 以上是我查询结果的一部分,查询出来3000多项,所以没办法手工去合并,希望高手能教下

写一个函数,运行sql调用函数,不知道你数据库字段名只是设前两个字段为id1,id2,这是我的思路 在我的数据库测试过好用

create function pmerg(@id1 int ,@id2 int)
returns varchar(8000)
as
begin
declare @s varchar(8000)
set @s=''
select @s=@s+';'+name from y where id1=@id1 and id2=@id2
set @s=right(@s,len(@s)-1)
return(@s)
End

上面是建立的函数,下面是要运行的sql
select distinct id1, id2, dbo.pmerg(id1,id2) from y

上面说的方法好象可以