我需要一种方法从表A中选择数据,连接具有相同索引的所有内容,并在索引1中更新表B,将连接结果与索引1相连表B的一行。
Table A
+-----------+------+-------+
| Type | Name | Index |
+-----------+------+-------+
| Cake | A | 1 |
+-----------+------+-------+
| Cookies | B | 1 |
+-----------+------+-------+
| Ice Cream | C | 1 |
+-----------+------+-------+
| Patatoes | D | 1 |
+-----------+------+-------+
| Cake | E | 2 |
+-----------+------+-------+
| Cookies | F | 2 |
+-----------+------+-------+
| Ice Cream | G | 2 |
+-----------+------+-------+
| Patatoes | H | 2 |
+-----------+------+-------+
决赛桌应该是:
Table B
+-------+---------------------------------------------+
| Index | Line |
+-------+---------------------------------------------+
| 1 | Cake A ; Cookies B; Ice Cream C, Patatoes D |
+-------+---------------------------------------------+
| 2 | Cake E ; Cookies F; Ice Cream G, Patatoes H |
+-------+---------------------------------------------+
你能帮帮我吗?
感谢
答案 0 :(得分:1)
假设您打算在预期输出中加上逗号而不是分号,可以使用listagg
:
select
"Index",
listagg(Type ||' '||Name, ', ') within group (order by Name) Line
from table_a
group by "Index";
要在table_b上进行更新,您可以使用merge
:
merge into table_b b
using (
select
"Index",
listagg(Type ||' '||Name, ', ') within group (order by Name) Line
from table_a
group by "Index"
) a on (
b."Index" = a."Index"
)
when matched then update
set b.Line = a.Line;
答案 1 :(得分:0)
只是上述方法的一种变化。这里我使用了WM_CONCAT函数来根据Index连接值。 注意:WM_CONCAT是oracle Undocumented Function,因此如果对象不在数据库中,则可能无效。 希望这也有帮助。
select idx,
wmsys.wm_concat(Typ) line -- This is Oracle undocumented function so may not work if this object not present in database
FROM
(SELECT 'Cake' typ,'A' name,1 idx FROM dual
UNION ALL
SELECT 'Cookies' typ,'B' name,1 idx FROM dual
UNION ALL
SELECT 'Ice Cream' typ,'C' name,1 idx FROM dual
UNION ALL
SELECT 'Cake' typ,'D' name,1 idx FROM dual
UNION ALL
SELECT 'Cake' typ,'E' name,2 idx FROM dual
UNION ALL
SELECT 'Cookies' typ,'F' name,2 idx FROM dual
UNION ALL
SELECT 'Ice Cream' typ,'G' name,2 idx FROM dual
)
GROUP BY idx;
MERGE INTO TABLEB USING
(SELECT idx,
wmsys.wm_concat(Typ) line
FROM
(SELECT 'Cake' typ,'A' name,1 idx FROM dual
UNION ALL
SELECT 'Cookies' typ,'B' name,1 idx FROM dual
UNION ALL
SELECT 'Ice Cream' typ,'C' name,1 idx FROM dual
UNION ALL
SELECT 'Cake' typ,'D' name,1 idx FROM dual
UNION ALL
SELECT 'Cake' typ,'E' name,2 idx FROM dual
UNION ALL
SELECT 'Cookies' typ,'F' name,2 idx FROM dual
UNION ALL
SELECT 'Ice Cream' typ,'G' name,2 idx FROM dual
)
GROUP BY idx
)a ON (a.idx = tableb.idx)
WHEN matched THEN
UPDATE SET tableb.line = a.line;