简体   繁体   中英

SQL concat column with one to many relationship

I would like some help creating an SQL sub statement which would show a concatenated string value using Table2 shown below:

SQL 连接表

For brevity see the following example of what I am trying to achieve:

SELECT *, CONCAT(Table2.TypeCode) ConcatField FROM Table1

Any help would be greatly appreciated, thank you.

This may be good:

WITH Concatetated AS (
    SELECT PrimaryId, '[' + STRING_AGG(TypeCode, '] [') + ']' AS "ConcatField"
    FROM Table2
    GROUP BY PrimaryId
)

SELECT t1."PrimaryId", t1."Name", c."ConcatField"
FROM Table1 t1
LEFT JOIN Concatetated c
  ON t1.PrimaryId = c.PrimaryId

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