postgresql - 仅在一列

时间:2015-12-31 05:19:25

标签: sql postgresql distinct aggregate-functions distinct-on

我有一张名为 eatable 的表格。它有类型,名称等列。

类型列的值为fruit, veggie, veggie, fruit, veggie

name 列有apple, brinjal, carrot, banana, cabbage。值

我希望输出为,type列必须只显示2行,name应显示所有值。

它应该如下:

eatable

我已尝试过以下查询,但不是我的预期:

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

帮帮我!!

1 个答案:

答案 0 :(得分:2)

您可以使用PostgreSQL的Aggregate Functions

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

结果:

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

OR

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

结果:

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

Demo