table 如下:
OrgID SubOrgID Code
1 1 1111
1 3 1212
1 4 4541
5 5 2121
5 6 1010
7 7 3212
输出如下:
1111 1111,1212,4541
2121 2121,1010
3212 3212
谢谢了。。。紧急中。。。
因不知道字段类型,故建表结构如下:
orgid int
suborgid int
code int
执行查询如下:
select code,STUFF((select ',' + convert(nvarchar,code)
from [org]
where orgid=o1.orgid
for xml path('')),1,1,'') as need
from org o1
where suborgid in (
select min(suborgid)
from org
group by orgid
)
1111 1111,1212,4541
2121 2121,1010
3212 3212
create function test_str
(
@id int
)
returns varchar(100)
as
begin
declare @a varchar(100)
set @a=''
select @a= @a+Code+',' from test where orid=@id --in(select distinct orid from test )
return @a
end
go
select distinct left(dbo.test_str(orid),charindex(',',dbo.test_str(orid))-1) ,dbo.test_str(orid) as code from test