简体   繁体   中英

Sql query , grouping result from left outer join to a single cell/field of main table

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM