Sql学习经典
在一个infor表中的数据如下:
age telnum
-----------------------
23 887907
23 807005
20 123456
21 21343
21 674542
请用SQL语句输出结果要是:
age telnum
-----------------------
23 887907,807005
20 123456
21 21343,674542
create table infor
(
age int,
telnum varchar(10)
)
insert into infor values (23,'887907')
insert into infor values (23,'807005')
insert into infor values (20,'123456')
insert into infor values (21,'21343')
insert into infor values (21,'674542')
go
create function getall(@a int)
returns varchar(8000)
as
begin
declare @str varchar(8000)
set @str = ''
select @str = @str + ',' + cast(telnum as varchar) from infor where age = @a
set @str = right(@str , len(@str) - 1)
return(@str)
End
go
select distinct age ,dbo.getall(age) as telnum from infor
--自己分析
declare @str varchar(8000)
set @str = ''
select @str = @str + ',' + cast(telnum as varchar) from infor where age='23'
select @str