如何在Oracle10g中按顺序连接多个行

时间:2015-07-07 07:08:02

标签: sql oracle oracle10g string-aggregation wm-concat

如果我有这样的数据:

GROUP  |  SEQUENCE  |  COMMAND
------------------------------
ONE    |     3      |  <message2>MESSAGE</message2>
ONE    |     1      |  <?xml version="1.0" encoding="UTF-8"?>
ONE    |     2      |  <message1>MESSAGE</message1>
TWO    |     2      |  <message2>MESSAGE</message2>
TWO    |     1      |  <?xml version="1.0" encoding="UTF-8"?>
........
TWO    |    10      |  <message9>MESSAGE</message9>

如何将命令连接成这样:

GROUP  |  COMMAND
-----------------
ONE    |  <?xml version="1.0" encoding="UTF-8"?>,<message1>MESSAGE</message1>,<message2>MESSAGE</message2>
TWO    |  <?xml version="1.0" encoding="UTF-8"?>,<message1>MESSAGE</message1>, .. ,<message9>MESSAGE</message9>

我在下面使用了这个查询,但是命令列根据它们的序列号不按顺序排列:

SELECT GROUP, WM_CONCAT(COMMAND) AS COMMAND
     FROM (SELECT GROUP, SEQUENCE, COMMAND FROM TBL ORDER BY SEQUENCE)
     GROUP BY GROUP

//AND THIS

SELECT GROUP, WM_CONCAT(DISTINCT COMMAND) AS COMMAND
 FROM (SELECT GROUP, SEQUENCE, COMMAND FROM TBL ORDER BY SEQUENCE)
 GROUP BY GROUP

任何建议和建议将不胜感激。 ^ _ ^

1 个答案:

答案 0 :(得分:1)

永远不要使用WM_CONCAT。阅读Why not use WM_CONCAT function in Oracle?

请参阅此主题https://stackoverflow.com/a/28758117/3989608

它没有记录,任何一直依赖WM_CONCAT功能的应用程序在升级到12c后将无效。因为,它已从最新的12c版本中删除。

有很多方法可以执行字符串聚合,具体取决于数据库版本。请参阅以下几个示例:

<强> 11gR2的

使用LIASTAGG

SQL> SELECT grp,
  2    listagg(command, ',') WITHIN GROUP(
  3  ORDER BY seq) command
  4  FROM t
  5  GROUP BY grp;

GRP COMMAND
--- --------------------------------------------------------------------------------------------
ONE <?xml version=1.0 encoding=UTF-8?>,<message1>MESSAGE</message1>,<message2>MESSAGE</message2>
TWO <?xml version=1.0 encoding=UTF-8?>,<message2>MESSAGE</message2>,<message9>MESSAGE</message9>

SQL>

9i及以上

使用ROW_NUMBER()SYS_CONNECT_BY_PATH

SQL> SELECT grp,
  2         LTRIM(MAX(SYS_CONNECT_BY_PATH(command,','))
  3         KEEP (DENSE_RANK LAST ORDER BY seq),',') command
  4  FROM   (SELECT grp,
  5                 command,
  6                 seq,
  7                 ROW_NUMBER() OVER (PARTITION BY grp ORDER BY seq) AS curr,
  8                 ROW_NUMBER() OVER (PARTITION BY grp ORDER BY seq) -1 AS prev
  9          FROM   t)
 10  GROUP BY grp
 11  CONNECT BY prev = PRIOR curr AND grp = PRIOR grp
 12  START WITH curr = 1;

GRP COMMAND
--- --------------------------------------------------------------------------------------------
ONE <?xml version=1.0 encoding=UTF-8?>,<message1>MESSAGE</message1>,<message2>MESSAGE</message2>
TWO <?xml version=1.0 encoding=UTF-8?>,<message2>MESSAGE</message2>,<message9>MESSAGE</message9>

SQL>