面试SQL题

来源:互联网 发布:淘宝好评没截图怎么办 编辑:程序博客网 时间:2024/05/03 08:50
面试曾遇到两个小题:第一个是按格式输出(多行合并成一行),第二个是查询出重复的数据行。
第一个是按格式输出(多行合并成一行):

mid   phone               myname 
1      13751345789  aaa 
2      13751345789  bbb 
3      13751345789  ccc 
4      13321254852  ddd 
5      13321254852  fff 
6      13568421314  zzz 

要求查询结果:
phone                names
13751345789  aaa,bbb,ccc
13321254852  ddd,fff
13568421314  zzz

实现代码如下:

 

--创建表
create table ms
(
mid 
int identity(1,1),
phone 
varchar(11),
myname 
varchar(20)
)

--插入数据
insert into ms
select '13751345789','aaa' union all
select '13751345789','bbb' union all
select '13751345789','ccc' union all
select '13321254852','ddd' union all
select '13321254852','fff' union all
select '13568421314','zzz'

--查看表数据
select * from ms

--创建函数
create function f_getName(@ph varchar(11))
returns varchar(1000)
as
begin 
declare @char varchar(1000)
set @char=''
select @char = @char + myname + ',' from ms where phone =@ph
return left(@char,len(@char)-1)--去掉最后一个逗号
end
go

--使用函数并显示结果
select distinct phone,dbo.f_getName(phone) as nm from ms

第二个是查询出重复的数据行:(使用上面的表)

--使用上面的表,查询出重复的数据行(大于1行)
select phone,count(phone) as times  from ms
group by phone
having count(phone)>1


原创粉丝点击