Oracle / SQL - 将多个记录合并为一个[字符串聚合]

时间:2012-02-22 22:47:09

标签: sql oracle oracle9i string-aggregation

我意识到这是一个荒谬的请求,但我想要做的是将多个记录与一些文字文本一起拉回到一个列中。

所以给出一个像这样的表

REGION  CITY    SID
-------------------
1   Chicago     1234
1   Palatine    567
1   Algonquin   234
1   Wauconda    987

我想看一个带有列的单个记录,像region这样的其他列很好,但是像这样的单个列

<option value="1234">Chicago</option><option value="567">Palatine</option><option value="234">Algonquin</option><option value="987">Wauconda</option>

有关如何做到这一点的任何想法?我正在运行Oracle 9i而不能在PL / SQL中执行此操作


好的表格格式有所改变,但想法是一样的

COUNTRY STORECODE   STORE_NAME
------------------------------
USA     1234        Chicago
USA     567         Palatine
CAN     987         Toronto

所以我发现这段代码通过列出的链接

SELECT COUNTRY,
       LTRIM(MAX(SYS_CONNECT_BY_PATH(STORECODE,','))
       KEEP (DENSE_RANK LAST ORDER BY curr),',') AS COUNTRY_HTML
FROM   (SELECT COUNTRY,
               STORECODE,
               ROW_NUMBER() OVER (PARTITION BY COUNTRY ORDER BY STORECODE) AS curr,
               ROW_NUMBER() OVER (PARTITION BY COUNTRY ORDER BY STORECODE) -1 AS prev
        FROM   tablename)
GROUP BY COUNTRY
CONNECT BY prev = PRIOR curr AND COUNTRY = PRIOR COUNTRY
START WITH curr = 1;

当我运行它时,我看到了这个输出

COUNTRY COUNTRY_HTML
--------------------
USA     1234,567
CAN     987

我的想法只是让我从另一个选择中选择内部选择拉出STORECODE和STORE_NAME,以及需要的html ......

SELECT COUNTRY,
       LTRIM(MAX(SYS_CONNECT_BY_PATH(RECORD_HTML,','))
       KEEP (DENSE_RANK LAST ORDER BY curr),',') AS COUNTRY_HTML
FROM   (SELECT COUNTRY,
               RECORD_HTML,
               ROW_NUMBER() OVER (PARTITION BY COUNTRY ORDER BY RECORD_HTML) AS curr,
               ROW_NUMBER() OVER (PARTITION BY COUNTRY ORDER BY RECORD_HTML) -1 AS prev
        FROM   (SELECT COUNTRY, '<option value="' || STORECODE || '">' || STORE_NAME || '</option>' AS RECORD_HTML FROM tablename))
GROUP BY COUNTRY
CONNECT BY prev = PRIOR curr AND COUNTRY = PRIOR COUNTRY
START WITH curr = 1;

当我尝试查看结果时,我们的前端环境确实接受了查询,但我收到错误:资源无效。在查看之前,您可能需要重新创建修复查询。

我知道这个错误可能没有用,但任何想法为什么我的版本不起作用?

谢谢!

3 个答案:

答案 0 :(得分:3)

这很令人作呕,但你可以这样做:

select replace(blah2,',','')
  from ( select wm_concat(blah) as blah2
           from ( select '<option value="' || sid || '">' || city || '</option>' as blah
                    from my_table
                         )
                 )

答案 1 :(得分:-2)

你玩过DBMS_XMLGEN吗?

答案 2 :(得分:-3)

您可以在Oracle中创建聚合函数,请参阅文档。