甲骨文設置:
CREATE TYPE VARCHAR2_TABLE AS TABLE OF VARCHAR2(4000);
/
CREATE OR REPLACE FUNCTION split_String(
i_str IN VARCHAR2,
i_delim IN VARCHAR2 DEFAULT ','
) RETURN VARCHAR2_TABLE DETERMINISTIC
AS
p_result VARCHAR2_TABLE := VARCHAR2_TABLE();
p_start NUMBER(5) := 1;
p_end NUMBER(5);
c_len CONSTANT NUMBER(5) := LENGTH(i_str);
c_ld CONSTANT NUMBER(5) := LENGTH(i_delim);
BEGIN
IF c_len > 0 THEN
p_end := INSTR(i_str, i_delim, p_start);
WHILE p_end > 0 LOOP
p_result.EXTEND;
p_result(p_result.COUNT) := SUBSTR(i_str, p_start, p_end - p_start);
p_start := p_end + c_ld;
p_end := INSTR(i_str, i_delim, p_start);
END LOOP;
IF p_start <= c_len + 1 THEN
p_result.EXTEND;
p_result(p_result.COUNT) := SUBSTR(i_str, p_start, c_len - p_start + 1);
END IF;
END IF;
RETURN p_result;
END;
/
CREATE TABLE Table1 (id, id2, "date") AS
SELECT 1, 2, DATE '2015-01-10' FROM DUAL UNION ALL
SELECT 2, 5, DATE '2015-06-13' FROM DUAL UNION ALL
SELECT 3, 9, DATE '2015-09-05' FROM DUAL UNION ALL
SELECT 4, 10, DATE '2015-02-11' FROM DUAL UNION ALL
SELECT 5, 26, DATE '2015-01-10' FROM DUAL UNION ALL
SELECT 6, 65, DATE '2015-01-25' FROM DUAL;
CREATE TABLE Table2 (id, id2, data) AS
SELECT 1, 2, '1.0,1.1,1.2' FROM DUAL UNION ALL
SELECT 2, 5, '1.0,1.1,1.2' FROM DUAL UNION ALL
SELECT 3, 9, '1.0,1.1,1.2' FROM DUAL UNION ALL
SELECT 4, 10, '3.2,3.3,4.5,6.7' FROM DUAL UNION ALL
SELECT 5, 26, '3.2,3.3,4.5,6.7' FROM DUAL UNION ALL
SELECT 6, 65, '3.2,3.3,4.5,6.7' FROM DUAL;
查詢:
SELECT t.id,
t.id2,
t."date",
d.column_value AS data
FROM (
SELECT MAX(t1.id ) KEEP (DENSE_RANK LAST ORDER BY t1."date") AS id,
MAX(t1.id2) KEEP (DENSE_RANK LAST ORDER BY t1."date") AS id2,
MAX(t1."date") AS "date",
t2.data
FROM Table1 t1
INNER JOIN
Table2 t2
ON (t1.id = t2.id AND t1.id2 = t2.id2)
GROUP BY t2.data
) t,
TABLE(SPLIT_STRING(t.data, ',')) d;
輸出:
ID ID2 date DATA
---------- ---------- ------------------- ----
3 9 2015-09-05 00:00:00 1.0
3 9 2015-09-05 00:00:00 1.1
3 9 2015-09-05 00:00:00 1.2
4 10 2015-02-11 00:00:00 3.2
4 10 2015-02-11 00:00:00 3.3
4 10 2015-02-11 00:00:00 4.5
4 10 2015-02-11 00:00:00 6.7
80是一個固定值,或者它可以從行更改爲行? – Aleksej
@Aleksej我已更新問題描述以使其更清晰。 – Dainy
問題是這個可怕的桌子設計。沒關係,只要'data'只包含一些字符串給你。但這種情況並非如此;你對存儲在'data'中的子串感興趣。但是,如果您對單獨的數據感興趣,那麼將其分開存儲!不要寫一個查詢來混淆這個混亂;改變你的數據庫。 –