Ross Goddard
Ross Goddard

Reputation: 4302

How do I join all values from multiple rows into a single row?

Lets say I have the query:

SELECT Foo FROM Bar

Which returns

Foo
A
B
C

What I really what is:
Foo
A,B,C

So all of the values from all of the rows has been collapsed into a single row (the commas are optional).
Is there a way to use a select statement to do this because I do not want to use cursors?

Upvotes: 0

Views: 853

Answers (5)

Fredou
Fredou

Reputation: 20100

 select max(a),max(b),max(c) from
 (
      select 'a' as a,null as b,null as c
      union
      select null,'b',null
      union
      select null,null,'c'
 ) as x

Upvotes: 0

Quassnoi
Quassnoi

Reputation: 425261

SELECT
    (   
    SELECT
      CASE
        WHEN ROW_NUMBER() OVER(ORDER BY bar) = 1 THEN ''
        ELSE ', '
      END + CAST(bar AS VARCHAR)
    FROM foo
    ORDER BY bar
    FOR XML PATH('')
    )

Upvotes: 1

dance2die
dance2die

Reputation: 36895

Try the following

declare @joined varchar(max)
set @joined = ''

select  @joined = @joined + IsNull(Foo + ',', '')
from    Bar (nolock)

--; Drop last "," if necessary
set @joined = substring(@joined, 1, len(@joined) - (case when len(@joined) > 0 then 1 else 0 end))
select  @joined as foo

Upvotes: 0

Lieven Keersmaekers
Lieven Keersmaekers

Reputation: 58431

Ross,

this should get you started.

  DECLARE @r VARCHAR(8000)
  SELECT @r = (SELECT DISTINCT Foo + ', ' FROM Bar FOR XML PATH(''))
  IF @r IS NOT NULL AND @r <> '' SET @r = SUBSTRING(@r, 1, LEN(@r)-1)
  SELECT @r

Upvotes: 0

LukeH
LukeH

Reputation: 269298

DECLARE @foos VARCHAR(4000)

SELECT @foos = COALESCE(@foos + ',', '') + Foo FROM Bar

SELECT @foos AS Foo

Upvotes: 2

Related Questions