我意識到這是一個荒謬的請求,但我想要做的是將多個記錄連同一些文本文本一起拉回到單個列。Oracle/SQL - 多記錄到一個[字符串聚合]
所以給定一個表像這樣
REGION CITY SID
-------------------
1 Chicago 1234
1 Palatine 567
1 Algonquin 234
1 Wauconda 987
我希望看到回單記錄與一列,例如區域等欄目都很好,但像這樣
<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
我的想法很簡單就是有內選擇拉從另一個選擇,我做我的商店代碼和STORE_NAME像這樣需要HTML沿CONCAT ......
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;
雖然我們的前端環境不接受當我嘗試查看結果時出現查詢錯誤:資源無效。在查看之前,您可能需要重新創建修復查詢。
我知道錯誤可能沒有幫助,但任何想法爲什麼我的版本不工作?
謝謝!
你真的,真的確定你不能在你的應用程序中做到這一點? – 2012-02-23 00:45:43
[在Oracle中快速生成連接字符串的方法]的可能重複(http://stackoverflow.com/questions/7531001/fast-way-to-generate-concatenated-strings-in-oracle) – 2012-02-23 02:59:34
WW。我當然會推動它,但如果我們不能或只是作爲一種學習練習,能夠做到這一點是非常好的。 – dscl 2012-02-23 14:12:21