日期:2014-05-18  浏览次数:20652 次

查询的难题阿
可能对大家来说不难,不过我是菜鸟
数据库表其中的两列
id1   id2
1       3
1       4
1       5
1       6
2       4
2       5
2       8
2       9
要求最后查询的样式为
id1   id2
1       3,4,5,6
2       4,5,8,9

------解决方案--------------------
alter function f_getstr(@id1 int)
returns varchar(2000)
as
begin
declare @s varchar(2000)
set @s= ' '
select @s=@s+ ', '+ltrim(id2) from 表
where id1=@id1
return stuff(@s,1,1, ' ')
end

select id1,dbo.f_getstr(id1)
from 表
group by id1
------解决方案--------------------
create table t(id1 int, id2 int)

insert t
select '1 ', '3 ' union all
select '1 ', '4 ' union all
select '1 ', '5 ' union all
select '1 ', '6 ' union all
select '2 ', '4 ' union all
select '2 ', '5 ' union all
select '2 ', '8 ' union all
select '2 ', '9 '


create function f(@id1 varchar(50))
returns varchar(100)
as
begin
declare @s varchar(100)
select @s=isnull(@s, ' ')+cast(id2 as varchar)+ ', ' from t where id1 = @id1
return left(@s,len(@s)-1)
end

select id1, dbo.f(id1) id2 from t
group by id1

drop table t
drop function f

-- result
id1 id2
----------- ----------------------
1 3, 4, 5, 6
2 4, 5, 8, 9

(所影响的行数为 2 行)