I have a data as shown below:

enter image description here

I want the output as shown below

enter image description here

in Postgress or in Excel.

New contributor
RISHAB GUPTA is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
  • 1
    Hi, and welcome to dba.se! What is the maximum number of people per loan? Jun 22 at 4:38
  • 1
    Don't do it with SQL, this is much better done in a tool like Excel - but a question how to do a "crosstab" in Excel is off-topic here. Jun 22 at 6:29

1 Answer 1


You can use a common table expression (CTE) to convert to an array of names and then access names by index to get your desired output.

WITH loan_names AS (
    SELECT loan_id
         , array_agg(customer_name) AS names
      FROM loan
     GROUP BY loan_id
SELECT loan_id
     , names[1] customer_name_1
     , names[2] customer_name_2
     , names[3] customer_name_3
  FROM loan_names

SQL does not allow for a variable number of columns, so you will need to decide how many names you want maximum. In this example you get a maximum of three. Adding names[4] would add a fourth, etc.

Your Answer

RISHAB GUPTA is a new contributor. Be nice, and check out our Code of Conduct.

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.