1

I have two tables, users_tbl and images tbl.

Every user can have more than one image.

I'm trying to select all the users and concatenate the user image in a single row

Example :

Users tbl

user_id    user_name
--------------------
 1          david
 2          tarik

images tbl

image_id   user_id   image_url 
-------------------------------
1            1      "image 12312 url"
2            1      "image 123 url"
3            1      "image 313 url"
4            1      "image 212 url"
5            2      "my image url"
5            2      "my image url2"

I need a select statement that returns the following result:

user_id   image_url 
----------------------------------------------------------------------
    1     "image 12312 url ,image 123 url,image 313 url,image 212 url"
    2     "my image url , my image url2"
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Tarik Husin
  • 197
  • 2
  • 9
  • Possible duplicate of https://stackoverflow.com/questions/13639262/optimal-way-to-concatenate-aggregate-strings. Use the XML PATH method pre-SQL 2017 and STRING_AGG in later versions. – Dan Guzman May 26 '19 at 12:52

1 Answers1

1

In SQL Server 2012, you would use for xml path:

select u.*,
       stuff( (select ', ' + i.image_url
               from images i
               where i.user_id = u.user_id
               for xml path ('')
              ), 1, 2, ''
            ) as image_urls
from users u;

EDIT:

If you want the comma at the end, leave out the stuff() and use:

select u.*,
       (select i.image_url + ', '
        from images i
        where i.user_id = u.user_id
        for xml path ('')
       ) as image_urls
from users u;
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786