在Oracle中将行组合成单个列

时间:2016-08-11 18:45:20

标签: oracle11g

有人知道如何将行组合成Oracle中的单个列吗?例如,假设我有这张表:

Customer   Bought
----------------------------
John       laptops
John       Phones
Lisa       Watches

我想要一个查询来生成以下格式:

Customer     CustomerBought
------------------------------------------
John         Laptops, Phones
Lisa         Watches

谢谢!

1 个答案:

答案 0 :(得分:2)

with data_qry (name, item)
as
(select 'John', 'Laptop' from dual union all
 select 'John', 'Phone' from dual union all
 select 'Lisa', 'Watches' from dual union all
 select 'Lisa', 'Glasses' from dual
 )
 select name, listagg(item, ', ') within group (order by item) as items
 from data_qry
 group by name