1

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.

2
  • 1
    Hi, and welcome to dba.se! What is the maximum number of people per loan?
    – Vérace
    Jun 22, 2022 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.
    – user1822
    Jun 22, 2022 at 6:29

1 Answer 1

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

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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