Reputation: 63
Let's say that i have the following 3 tables :
IDUser Name Surname
1 Lucas Wurth
2 John Charson
3 Erik Drown
IDUser IDLocation
1 1
1 2
2 1
3 2
IDLocation Name
1 Rome
2 Milan
a User Table , a Location table , and a table to assign a location to our users. I'd like to extract from my database all the users and have a specific column where all assigned locations are reported like so:
IDUser Name Surname Locations
1 Lucas Wurth Rome - Milan
2 John Charson Rome
3 Erik Drown Milan
Note that the user 1 has both Rome & Milan assigned
Currently my query:
SELECT
U.IDUser,
U.Name,
U.Surname,
UL.Name AS LocationName
FROM Users U
LEFT OUTER JOIN UserLocation UL ON
UL.IDUser = U.IDUser
LEFT OUTER JOIN Location L ON
UL.IDLocation = L.IDLocation
Is obviously returning a total of 4 records instead of 3 , is it possible to achievie this using the aggregate function group by? and if so how should i do this?
Upvotes: 1
Views: 339
Reputation: 526
If you are using SqlServer you can use STRING_AGG :
SELECT
U.IDUser,
U.Name,
U.Surname,
STRING_AGG(UL.Name, ' - ') AS Locations
FROM Users U
LEFT OUTER JOIN UserLocation UL
ON UL.IDUser = U.IDUser
LEFT OUTER JOIN Location L
ON UL.IDLocation = L.IDLocation
GROUP BY U.IDUser, U.Name, U.Surname
Upvotes: 1