I have a data as shown below:
I want the output as shown below
in Postgress or in Excel.
Database Administrators Stack Exchange is a question and answer site for database professionals who wish to improve their database skills and learn from others in the community. It only takes a minute to sign up.
Sign up to join this communityYou 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.