1

Possible Duplicate:
Simulating group_concat MySQL function in MS SQL Server 2005?
Concat field value to string in SQL Server

There are 2 tables involved, Users and Keywords.

Users
userId
firstName
lastName
...

Keywords
userId
keyword

If I run this query:

select u.userId, u.firstName, u.lastName, k.keyword 
from Users as u 
inner join  Keywords as k on u.userId = k.userId

I get something like this:

enter image description here

What I want is this:

enter image description here

This looked very similar to what I wanted but I can't seem to get it to work right.

Community
  • 1
  • 1
ryoung
  • 856
  • 1
  • 8
  • 24

3 Answers3

1
SELECT
       u.userId,
       u.firstName,
       u.lastName,
       (select keyword +', ' from Keywords tk where tk.userid= u.userid for xml path ('')  )   as keyword
  FROM
       Users AS u 

Sample query to test:

declare @Users as table(
userid int,
firstname varchar(20),
lastname varchar(20)

)

declare @Keywords as table(
userid int,
keyword varchar(20)

)

insert into @Users
values(
1, 'Bob','Sanders'
),
(
2, 'Jamie','Smith'
)

insert into @Keywords
values 
(1,'Cars'),
(1,'Pizza'),
(2,'Tomato'),
(2,'Blah')

SELECT
       u.userId,
       u.firstName,
       u.lastName,
       (select keyword +', ' from @Keywords tk where tk.userid= u.userid for xml path ('')  )   as keyword
  FROM
       @Users AS u 

Returns:

userId  firstName   lastName    keyword
1       Bob         Sanders     Cars, Pizza, 
2       Jamie       Smith       Tomato, Blah, 
Icarus
  • 63,293
  • 14
  • 100
  • 115
1
;WITH a AS (
  SELECT 
    u.userId,
    u.firstName,
    u.lastName,
    ( SELECT k.keyword + ',' 
      FROM Keywords k
      WHERE k.userId = u.userId
      ORDER BY k.keyword
      FOR XML PATH('') 
    ) AS [keyword]
  FROM Users u
)
SELECT 
  a.userId,
  a.firstName,
  a.lastName,
  -- strip off trailing comma
  LEFT(
    a.keyword, 
    LEN(a.keyword)-1
  ) AS keyword
FROM a   
Sean
  • 7,562
  • 10
  • 27
  • 29
0

You can create a new sql aggregate function concat to concatenate texts and use if in you query:

select userId, firstName, Lastname, concat(Keyword)
from Users
group by userId, firstName, Lastname;

Follwoing link shows an example on how to create the concat funcion. http://msdn.microsoft.com/en-us/library/ms182741.aspx

Raihan
  • 10,095
  • 5
  • 27
  • 45