sql逗号合并
A. sql Server如何将Id相同的字段合并,并且以逗号隔开
需要用到stuff函数:
例:
id name
1 张三
1 李四
指游 2 王五
2 赵六
结果:
Id name
1 张三,李四
2 王五,赵六念逗旁
创建测试表及插入数据:
createtabletest
(idint,
namevarchar(10))
insertintotestvalues(1,'张三')
insertintotestvalues(1,'李四')
insertintotestvalues(2,'王五')
insertintotestvalues(2,'赵六')
执行语仔橡句:
selectid,stuff((select','+namefromtest
wherea.id=idforxmlpath('')),1,1,'')asname
fromtestasagroupbyid
执行结果截图:
B. sql查询结果逗号拼接出来
--这个与字段的类型的长度关系很大,不然出来ckid中间的空格太长不好看
createtabletable1
(
midchar(2),
qidchar(5),
ckidchar(5)
)
insertintotable1
select'A1','KD001','ck001'unionall
select'A1','KD001','ck003'unionall
select'B1','QS123','cd111'unionall
select'B1','QS123','cd112'unionall
select'C1','RT001','rt115'unionall
select'C1','RT001','cf001'unionall
select'C1','RS156','yu116'
--使用forxmlpath
selecta.mid,a.qid,(selectckid+','fromtable1bwherea.mid=b.midanda.qid=b.qidforxmlpath(''))ckidfromtable1agroupbya.mid,a.qid
--或者下面这个使用stuffforxmlpath
selecta.mid,a.qid,stuff((select','+ckidfromtable1bwherea.mid=b.midanda.qid=b.qidforxmlpath('')),1,1,'')ckidfromtable1agroupbya.mid,a.qid
C. sql 如何将查出来的一列用逗号拼接
写个存储过程,声明一个结果用的varchar变量,用游标把读出来的字脊吵段拼出来,照着下边的改改就行了
create proc [dbo].[teststr]asbegin declare @result VARCHAR(max)--用来处理结果的变量 declare @resultt VARCHAR(10) set @result=''
begin try deallocate tmpc end try begin catch end catch
declare tmpc cursor for select deviceid from t_carinfo Open tmpc --循环蠢册并提取记录 Fetch Next From tmpc Into @resultt--取第一条记录存入@resultt中 While ( @@Fetch_Status=0 ) begin set @result=@result+','+@resultt Fetch Next From tmpc into @resultt----下一条 end --关闭游标 Close tmpc --释放游带野宏标 Deallocate tmpc print substring(@result,2,len(@result)-1)--这里就是把第一个逗号去掉,取全部的数据end
D. pgsql 如何把多行字符串用逗号拼接起来
可以通过“||”拼接的方式实现兄蔽顷.
sql:select t.name||','||t.age from tablename t;
解释:oracle中用“||”来进行字符串拼羡陆接,上面的就会出现如并拿“zhangsan,15”的样式。