How to select rows which have same set of values in two columns and hence concatenate the values in the third column?

587 views Asked by At

Attached Image

I have the sample values as shown in the image attached. What I want to achieve is that the value of PR_NUMBER field gets concatenated on the basis of same values in PO_NUMBER and PO_ITEM.

Though this is a sample data, any n number of rows can have the same values and hence the concatenation of all such values in the PR_NUMBER column need to be done.

I got to know about CURSORS to loop through the table but don't really know what to do with them.

Expected output image is

123 | 1 | 5678,6789
456 | 1 | 2322,3432
456 | 2 | 4678
2

There are 2 answers

2
ScaisEdge On BEST ANSWER

If you are using SAP HANA then you can use STRING_AGG(Name, ',')

 SELECT po_number, po_item, STRING_AGG(pr_number, ',')
 from your_table
 group by po_number, po_item;

instead if you are using mysql you can use group_concat

 SELECT po_number, po_item, group_concat(pr_number, ',')
 from your_table
 group by po_number, po_item;
1
Gordon Linoff On

You are looking for group_concat():

select po_number, po_item, group_concat(pr_number)
from t
group by po_number, po_item;