以逗号为分隔符将多行转换为一行 [英] Convert multiple rows into one with comma as separator
本文介绍了以逗号为分隔符将多行转换为一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我发出 SELECT username FROM Users
我得到这个结果:
但我真正需要的是一行,其中所有值以逗号分隔,如下所示:
<前>保罗、约翰、玛丽我该怎么做?
解决方案
这应该适合你.一直测试到 SQL 2000.
create table #user (username varchar(25))插入#user(用户名)值('Paul')插入#user(用户名)值('John')插入#user(用户名)值('Mary')声明@tmp varchar(250)SET @tmp = ''选择 @tmp = @tmp + 用户名 + ', ' from #user选择 SUBSTRING(@tmp, 0, LEN(@tmp))
If I issue SELECT username FROM Users
I get this result:
username -------- Paul John Mary
but what I really need is one row with all the values separated by comma, like this:
Paul, John, Mary
How do I do this?
解决方案
This should work for you. Tested all the way back to SQL 2000.
create table #user (username varchar(25))
insert into #user (username) values ('Paul')
insert into #user (username) values ('John')
insert into #user (username) values ('Mary')
declare @tmp varchar(250)
SET @tmp = ''
select @tmp = @tmp + username + ', ' from #user
select SUBSTRING(@tmp, 0, LEN(@tmp))
这篇关于以逗号为分隔符将多行转换为一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文