Oracle 多行数据合并成一行数据

方法一

SQL> WITH SHOPPING AS
  2  (
  3      SELECT '1' U_ID, '苹果' GOODS, '2' QTY FROM DUAL UNION ALL
  4      SELECT '2' U_ID, '梨子' GOODS, '5' QTY FROM DUAL UNION ALL
  5      SELECT '1' U_ID, '西瓜' GOODS, '4' QTY FROM DUAL UNION ALL
  6      SELECT '3' U_ID, '葡萄' GOODS, '1' QTY FROM DUAL UNION ALL
  7      SELECT '3' U_ID, '香蕉' GOODS, '1' QTY FROM DUAL UNION ALL
  8      SELECT '1' U_ID, '橘子' GOODS, '3' QTY FROM DUAL
  9  )
 10  SELECT U_ID, WMSYS.WM_CONCAT(GOODS) GOODS_SUM
 11  FROM   SHOPPING
 12  GROUP BY U_ID;
U_ID GOODS_SUM
---- --------------------------------------------------------------------------------
1    苹果,橘子,西瓜
2    梨子
3    葡萄,香蕉

 方法二

SQL> WITH SHOPPING AS
  2  (
  3      SELECT '1' U_ID, '苹果' GOODS, '2' QTY FROM DUAL UNION ALL
  4      SELECT '2' U_ID, '梨子' GOODS, '5' QTY FROM DUAL UNION ALL
  5      SELECT '1' U_ID, '西瓜' GOODS, '4' QTY FROM DUAL UNION ALL
  6      SELECT '3' U_ID, '葡萄' GOODS, '1' QTY FROM DUAL UNION ALL
  7      SELECT '3' U_ID, '香蕉' GOODS, '1' QTY FROM DUAL UNION ALL
  8      SELECT '1' U_ID, '橘子' GOODS, '3' QTY FROM DUAL
  9  )
 10  SELECT U_ID, SUBSTR(MAX(SYS_CONNECT_BY_PATH(GOODS, ',')), 2)  GOODS_SUM
 11  FROM (
 12      SELECT U_ID, GOODS, ROW_NUMBER() OVER(PARTITION BY U_ID ORDER BY U_ID) RN
 13      FROM   SHOPPING
 14  )
 15  GROUP BY U_ID
 16  START WITH RN = 1
 17  CONNECT BY PRIOR RN = RN - 1 AND PRIOR U_ID = U_ID
 18  ORDER BY U_ID;
U_ID GOODS_SUM
---- --------------------------------------------------------------------------------
1    葡萄,香蕉,橘子
2    梨子
3    葡萄,香蕉

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值