2016-01-18 71 views
2

所以,我目前有兩個表,一個包含每個對象的固定部分,另一個包含每個對象的可變數目的屬性作爲鍵/值對。我想將這些屬性轉換爲JSON映射格式的主表中的CLOB字段。UPDATE SQL查詢中的聚合

create table test_a (id integer, properties clob); 
create table test_b (id integer, a_id integer, key char(30), value char(30)); 

insert into test_a values(1,''); 
insert into test_a values(2,''); 
insert into test_a values(3,''); 

insert into test_b values (1, 1, 'k1', 'v1'); 
insert into test_b values (2, 1, 'k2', 'v2'); 
insert into test_b values (3, 2, 'k3', 'v3'); 
insert into test_b values (4, 2, 'k4', 'v4'); 
insert into test_b values (5, 2, 'k5', 'v5'); 
insert into test_b values (6, 2, 'k6', 'v6'); 

我可以構建JSON我通過下面的查詢想:

WITH PROPS AS 
    (SELECT '"' 
    ||trim(KEY) 
    ||'":"' 
    ||trim(value) 
    ||'"' json, 
    test_b.* 
    FROM test_b 
) 
SELECT test_a.id, 
    '{' 
    || 
    (SELECT listagg(json, ',') within GROUP (
    ORDER BY props.key) 
    FROM PROPS 
    WHERE PROPS.A_ID = test_a.id 
) 
    || '}' 
FROM TEST_A 
INNER JOIN PROPS 
ON TEST_A.ID = PROPS.A_ID 
GROUP BY TEST_A.ID ; 

我得到期望的結果

1 "{""k1"":""v1"",""k2"":""v2""}" 
2 "{""k3"":""v3"",""k4"":""v4"",""k5"":""v5"",""k6"":""v6""}" 

但是當我嘗試使用這個結果插入到主表,我得到錯誤

UPDATE TEST_A SET PROPERTIES = (
WITH PROPS AS 
    (SELECT '"' 
    ||trim(key) 
    ||'":"' 
    ||trim(value) 
    ||'"' json, 
    test_b.* 
    FROM test_b 
) 
SELECT '{' 
    || 
    (SELECT listagg(json, ',') within GROUP (order by props.key) FROM PROPS 
    WHERE PROPS.A_ID = test_a.id) 
    || '}' from TEST_A INNER JOIN PROPS ON TEST_A.ID = PROPS.A_ID GROUP BY TEST_A.ID 
) ; 

Error report - 
SQL Error: ORA-01427: single-row subquery returns more than one row 
01427. 00000 - "single-row subquery returns more than one row" 

有什麼想法?

回答

2

您需要相關子查詢而不是group by。整個外部查詢看起來不正確,所以我認爲你需要這樣的東西:

UPDATE TEST_A 
    SET PROPERTIES = (
     WITH PROPS AS (
       SELECT '"'||trim(key)||'":"'||trim(value)||'"' as json, 
        test_b.* 
       FROM test_b 
      ) 
     SELECT '{' || listagg(json, ',') within GROUP (order by props.key) || '}' 
     FROM PROPS 
     WHERE PROPS.A_ID = test_a.id 
     ) ; 
+0

神奇,像一個魅力工程 – user2650994