項目中遇到一個需求,需要將多行合并為一行。
表結構如下:
NAME Null Type
------------------------ --------- -----
N_SEC_CODE NOT NULL CHAR(6)
C_RESEARCHER_CODE NOT NULL VARCHAR2(20)
此表儲存了“股票”與“研究員”的對應關係資料,一般而言,對於同一隻股票而言,可能有多個研究員
對其進行跟蹤研究。所以目前遇到一個要求,需查詢出每隻股票和對應的研究員(研究員代碼間,使用逗號分隔)。
例如有如下資料:
000297 chenpeng
000297 liusu
合并處理後需顯示為:
000297 chenpeng,liusu
方法1:
SELECT
n_sec_code, TRANSLATE (
LTRIM
(
text
,
'
/
'
),
'
*/
'
,
'
*,
'
) researcherList
FROM
(
SELECT
ROW_NUMBER ()
OVER
(PARTITION
BY
n_sec_code
ORDER
BY
n_sec_code,
lvl
DESC
) rn,
n_sec_code,
text
FROM
(
SELECT
n_sec_code,
LEVEL
lvl,
SYS_CONNECT_BY_PATH (c_researcher_code,
'
/
'
)
text
FROM
(
SELECT
n_sec_code, c_researcher_code
as
c_researcher_code,
ROW_NUMBER ()
OVER
(PARTITION
BY
n_sec_code
ORDER
BY
n_sec_code,c_researcher_code) x
FROM
m_researcher_stock_rel
ORDER
BY
n_sec_code, c_researcher_code) a
CONNECT
BY
n_sec_code
=
PRIOR n_sec_code
AND
x
-
1
=
PRIOR x))
WHERE
rn
=
1
ORDER
BY
n_sec_code;
方法2(10g):
SELECT n_sec_code, wmsys.wm_concat (c_researcher_code) as result
FROM m_researcher_stock_rel
GROUP BY n_sec_code
http://www.cnblogs.com/heekui/archive/2009/07/30/1535516.html