请问数据库查询的问题

来源:百度知道 编辑:UC知道 时间:2024/05/18 23:11:49
请问oracle 查询能否实现这样的事情

table

type name

1 张三

1 李四

2 王五

2 陈六

查出来的数据 根据type合并那么 比如 1 张三 李四
2 王五 陈六

--建表
create table tb(id int, value varchar(10))
insert into tb values(1, 'aa')
insert into tb values(1, 'bb')
insert into tb values(2, 'aaa')
insert into tb values(2, 'bbb')
insert into tb values(2, 'ccc')
go
--建函数
CREATE FUNCTION dbo.f_str(@id int)
RETURNS varchar(8000)
AS
BEGIN
DECLARE @r varchar(8000)
SET @r = ''
SELECT @r = @r + ',' + value FROM tb WHERE id=@id
RETURN STUFF(@r, 1, 1, '')

END

GO
-- 调用函数
SELECt id, value = dbo.f_str(id) FROM tb GROUP BY id

drop table tb
drop function dbo.f_str