Hi
I have a table with field BPLId. I want to query another table which have same BPLId and then concatenate LocCode field from another table
which have same DocNum of that same BPLId records using Sql Query.
Thanks
Hi
I have a table with field BPLId. I want to query another table which have same BPLId and then concatenate LocCode field from another table
which have same DocNum of that same BPLId records using Sql Query.
Thanks
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Tuhin PaulPosted Apr 1, 2025, 6:41 AM
Example Data
Table1 (
Table1):BPLId
DocNum
1
101
1
102
2
103
Table2 (
Table2):BPLId
LocCode
1
A
1
B
1
C
2
X
2
Y
Result:
BPLId
DocNum
ConcatenatedLocCodes
1
101
A, B, C
1
102
A, B, C
2
103
X, Y
Tuhin PaulPosted Apr 1, 2025, 6:37 AM
In PostgreSQL, you can use the
STRING_AGGfunction.STRING_AGGis used to concatenateLocCodevalues with a specified delimiter (', ').ORDER BYclause insideSTRING_AGGensures the concatenated values are sorted.In SQL Server, you can use the
STRING_AGGfunction (introduced in SQL Server 2017) orFOR XML PATHfor older versions.Using
STRING_AGG(SQL Server 2017+):Using
FOR XML PATH(Older Versions):STUFFremoves the leading delimiter (,) from the concatenated string.FOR XML PATH('')is used to concatenate values into a single string.Tuhin PaulPosted Apr 1, 2025, 6:36 AM
To achieve this, you can use a combination of SQL
JOINand string aggregation functions (likeGROUP_CONCATin MySQL orSTRING_AGGin PostgreSQL/SQL Server).BPLId.DocNumand concatenate theLocCodevalues for each group.In MySQL, you can use the
GROUP_CONCATfunction to concatenate values.t1represents the first table (Table1) withBPLIdandDocNum.t2represents the second table (Table2) withBPLIdandLocCode.JOINensures that only rows with matchingBPLIdin both tables are considered.GROUP_CONCATconcatenates theLocCodevalues for eachDocNumgroup.ORDER BY t2.LocCodeensures the concatenated values are sorted alphabetically.SEPARATOR ', 'specifies the delimiter between concatenated values.Sangeetha SPosted Apr 1, 2025, 4:24 AM
Let's consider you have two tables:
Table1with fieldsBPLIdandDocNumTable2with fieldsBPLId,DocNum, andLocCodeYou want to concatenate the
LocCodefield fromTable2for records with the sameBPLIdandDocNum.Here's how you can do it:
Explanation:
Table1andTable2whereBPLIdandDocNummatch.LocCodevalues fromTable2into a single string, separated by commas.BPLIdandDocNum.If you are using MySQL, you can use
GROUP_CONCATinstead: