monkey_boys
monkey_boys

Reputation: 7348

Grouping Query Help in sql server 2005?

My table TEST has the following rows:

test    | 1
test    | 2
test    | 3

How I query it to get the following result?

test    | 1 - 2 - 3

Upvotes: 1

Views: 97

Answers (2)

OMG Ponies
OMG Ponies

Reputation: 332531

Try:

SELECT x.column1,
       STUFF(SELECT ' - ' + t.column2
               FROM TEST t
              WHERE t.column1 = x.column1
           ORDER BY t.column1
            FOR XML PATH(''), 1, 1, '')
  FROM TEST x

Reference: STUFF

Upvotes: 1

Craig Bart
Craig Bart

Reputation: 75

You can use the Coalesce function to sort you numbers in a list. Hopefully this gives you a start:

Declare @T as Table (Col1 varchar(35), Col2 int)

Insert into @T(Col1, Col2)
Select 'Test', 1

Insert into @T(Col1, Col2)
Select 'Test', 2

Insert into @T(Col1, Col2)
Select 'Test', 3


DECLARE @X varchar(200)

SELECT @X = COALESCE(@X + ' - ', '') + Cast(Col2 as varchar(5))
From @T

Select @X

Upvotes: 1

Related Questions