我有一个包含三列的服务表。
服务
sr_id lang alias
1 EN A
1 PA B
1 HI C
2 EN D
2 HI E
现在,我想输出每个服务id,lang和alias列将是服务别名的串联。
示例输出 -
SR_ID lang alias
1 EN A,B,C
1 PA A,B,C
1 HI A,B,C
2 EN D,E
2 HI D,E
如何使用PostgreSQL 9.4?
答案 0 :(得分:3)
如果您不需要排序,可以使用:
select sr_id, lang, string_agg(alias, ',') over () as alias
from services
order by sr_id;
否则你需要:
select s.sr_id, s.lang, t.alias
from services s
join (
select sr_id, string_agg(alias, ',' order by alias) as alias
from services
group by sr_id
) t on t.sr_id = s.sr_id
order by s.sr_id;
答案 1 :(得分:1)
试图用相同的样本数据创建类似的条件。请查看以下查询
select a.sr_id , a.lang, b.ALIAS from
SERVICES a ,
(
select sr_id , string_agg(ALIAS::text,',') ALIAS
from SERVICES
group by sr_id) b
where a.sr_id = b.sr_id;