sql server - How to coalesce many rows into one? -


i using ssms 2008 r2 , trying coalesce many rows one. should simple think, repeating data in each row. consider:

create table test ( name varchar(30) ) insert test values('a'),('b'),('c') select * test  select distinct name, coalesce(name + ', ', '') test  

how can rewrite achieve 1 row like: a,b,c

in sql server transact-sql, easiest way accomplish following.

a table this:

create table #foo (   id   int         not null identity(1,1) primary key clustered ,   name varchar(32) not null , )  insert #foo (name) values ( 'a' ) insert #foo (name) values ( 'b' ) insert #foo (name) values ( 'c' ) insert #foo (name) values ( 'd' ) go 

can flattened using seemingly dubious (but documented) technique:

declare @text varchar(max) = ''  select @text = @text              + case len(@text)                  when 0 ''                  else        ','                end              + t.name #foo t  select list_of_names = @text go 

yielding

list_of_names ------------- a,b,c,d 

easy!


Comments

Popular posts from this blog

apache - Remove .php and add trailing slash in url using htaccess not loading css -

javascript - jQuery show full size image on click -