0

I have a table called eatable. It has columns such as type, name.

type column has fruit, veggie, veggie, fruit, veggie values .

name column has apple, brinjal, carrot, banana, cabbage.values

I want the output as, type column must display only 2 rows and name should display all the values.

It should like below:

eatable

I have tried the below query, but it isn't I am expected:

select distinct on (type) type, name from eatable;

Help me out!!

0

1 Answer 1

2

You can use PostgreSQL's Aggregate Functions

SELECT type
    ,string_agg(NAME, ',') "name"
FROM eatable
GROUP BY type;

Result:

type   name  
text   text                 
------ ---------------------- 
fruit  apple,banana           
veggie brinjal,carrot,cabbage 

OR

SELECT type
    ,array_agg(name) "name"
FROM eatable
GROUP BY type;

Result:

type   name  
text   text[]                   
------ ------------------------ 
fruit  {apple,banana}           
veggie {brinjal,carrot,cabbage} 

Demo

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.