用SQL將Oracle中同一列的多行記錄拼接成一個字串
阿新 • • 發佈:2019-02-06
-- 原始資料 -- a 111 -- b 222 -- a 333 -- a 444 -- b 555 -- 最終結果 -- a 111*333*444 SELECT L4.L_TIME ,MAX(SUBSTR(L4.分組內容,2)) 最終欄位值 FROM( SELECT L3.L_TIME ,SYS_CONNECT_BY_PATH(L3.L_CONTENT,'*') AS 分組內容 FROM( SELECT L2.L_TIME ,L2.L_CONTENT ,L2.L_TIME||L2.分組內編號 AS 分組欄位加編號,L2.L_TIME||(L2.分組內編號-1) AS 上級分組欄位加編號 FROM( SELECT L1.L_TIME -- 分組依據 ,L1.L_CONTENT -- 同一列中 要合併的不同行 的值 ,ROW_NUMBER() OVER (PARTITION BY L1.L_TIME ORDER BY L1.L_CONTENT ASC) 分組內編號 FROM LOGS L1 ) L2 ) L3 START WITH L3.上級分組欄位加編號 LIKE '%0' CONNECT BY PRIOR L3.分組欄位加編號=L3.上級分組欄位加編號 ) L4 WHERE L_TIME='111' GROUP BY L4.L_TIME -- ROW_NUMBER() OVER(PARTITION BY A ORDER BY B DESC) 新列名 -- 根據A分組,在分組內部根據B排序,而此函式計算的值就表示每組內部排序後的順序編號(組內連續的唯一的) -- SYS_CONNECT_BY_PATH 函式: 第一個引數是形成樹形式的欄位,第二個引數是父級和其子級分隔顯示用的分隔符 -- CONNECT BY PRIOR 是標示父子關係的對應 -- START WITH 代表你要開始遍歷的的節點 ------------------------------------------------------------------------------------------ ------------------------------------------------------------------------------------------ 附上建表語句: DROP TABLE LOGS; CREATE TABLE LOGS ( L_ID VARCHAR2(32) NOT NULL , L_CONTENT VARCHAR2(512) , L_TIME VARCHAR2(32) , L_USER VARCHAR2(32) , PRIMARY KEY (L_ID) ); COMMENT ON TABLE LOGS IS '日誌表'; COMMENT ON COLUMN LOGS.L_ID IS '日誌ID'; COMMENT ON COLUMN LOGS.L_CONTENT IS '日誌內容'; COMMENT ON COLUMN LOGS.L_TIME IS '時間'; COMMENT ON COLUMN LOGS.L_USER IS '操作人'; INSERT INTO LOGS (L_ID, L_CONTENT, L_TIME, L_USER) VALUES ('123', '黑啊', '111', '12345'); INSERT INTO LOGS (L_ID, L_CONTENT, L_TIME, L_USER) VALUES ('124', '白啊', '222', '123456'); INSERT INTO LOGS (L_ID, L_CONTENT, L_TIME, L_USER) VALUES ('125', '黑白啊', '111', '1234567'); INSERT INTO LOGS (L_ID, L_CONTENT, L_TIME, L_USER) VALUES ('126', '白白啊', '111', '12345'); INSERT INTO LOGS (L_ID, L_CONTENT, L_TIME, L_USER) VALUES ('127', '嘿嘿啊', '222', '123456');