Create TableTB ([ID] int,[name] varchar(2))Insert intoTBSelect 1,'AA' Union AllSelect 2,'BB' Union AllSelect 1,'cc' Union AllSelect 3,'DD' Union AllSelect 2,'ee' Select * fromTB--EnquirySelectID, name=Stuff((Select ','+Name fromTbwhereId=T.id forXML Path ("')),1,1,"') fromTB TGroup byID Method Two:CREATE FUNCTIONGet_string (@ID INT)RETURNS VARCHAR( -) as BEGIN DECLARE @NAME VARCHAR( -) SELECT @NAME=ISNULL(@NAME+',',"')+NAME fromTBWHEREId=@ID RETURN @NAME ENDSELECTID, DBO. Get_string (ID) NAME fromTBGROUP byID-----------------------------------------------------------------------in Oracle, there is the corresponding function, the Sys_connect_by_path function. Let's write the Oracle function implementation here.SelectID, Itrim (Max(Sys_connect_by_path (Name,','))) asname from (SelectID, name, lead (Rnfirst) Over(Partition byNoOrder byrnfirst) Rnnext from (Selecta.id, A.name, Row_number () Over(Order byA.id,a.namedesc) Rnfirst from @ta) tmpTable1) Tmptable2start withRnnext is NULLConnect byRnnext=PRior RnfirstGroup byThe above ID is the way to implement row-to-column in Oracle. ********************************************Let's take a look at SQL Server, because SQL Server does not provide a similar function, do not know that sqlserver2012 is not available, but SQL Server support is also very simple, using the cross apply and for XML path combination to use, These two alone know what is going on, how to use, but really do not know that there are two combinations to complete this function, it is very incredible, here to thank the people on the network, the original write their own things are to learn the knowledge recorded to the machine, from not put to the Internet, it may be recently bar, a lot of work will not, All through the network help, put everything I know also put on the Internet, we learn together. SQL Server:SelectIdSUBSTRING(Names,1,Len(names)-1) from @t asA CrossAPPLY (SELECTNAME+ ',' from @t asBWHEREa.ID=b.ID forXML PATH ("')) D (names)GROUP byID, names
1 aa,cc 2 bb,ee 3 DD
SQL Server measured effectively
The above content is transferred from
http://new-fighter.iteye.com/blog/1537533
SQL Server Oracle string concatenation