在Oracle中合并两行

j2cgzkjk  于 2022-10-04  发布在  Oracle
关注(0)|答案(1)|浏览(163)

我在甲骨文有一张table,这张table已经从一些更大的table上取走了

+---------------+------------+
| shop   number | Model Type |  
+---------------+------------+
| 1             | Mod-1      |  
+---------------+------------+
| 1             | Mod-2      |  
+---------------+------------+
| 2             | Mod-3      | 
+---------------+------------+
| 2             | Mod-3      | 
+---------------+------------+
| 3             | Mod-4      |
+---------------+------------+
| 3             | Mod-5      |
+---------------+------------+
| 4             | Mod-1      |
+---------------+------------+
| 4             | Mod-2      | 
+---------------+------------+
| 4             | Mod-6      | 
+---------------+------------+
| 4             | Mod-3      |
+---------------+------------+
| 5             | Mod-1      |
+---------------+------------+

实际上,这是将基于shop的行组合在一个位置,并在此基础上生成两个不同的列,结果应该如下所示

+---------------+---------------------------------+-----------+
| shop   Number | Shop Type                       | Shop Type |
+---------------+---------------------------------+-----------+
| 1             | Mod-1 & Mod-2                    | Mix       |
+---------------+---------------------------------+-----------+
| 2             | Mod-3                           | Mod-3     |
+---------------+---------------------------------+-----------+
| 3             | Mod-4 & Mod-5                   | Mix       |
+---------------+---------------------------------+-----------+
| 4             | Mod-1 & Mod-2   & Mod-3 & Mod-6 | Mix       |
+---------------+---------------------------------+-----------+
| 5             | Mod-1                           | Mod-1     |
+---------------+---------------------------------+-----------+

不确定如何处理此问题。请帮助...

uoifb46i

uoifb46i1#

您可以使用以下SQL

select shop_number,
listagg(distinct model_type, ' & ') within group (order by model_type) shop_type,
decode(count(distinct model_type), 1, max(model_type), 'Mix') shop_type
from mytable
group by shop_number;

请注意,在19c中添加了listagg()中的关键字distinct。如果您使用的是旧版本,则需要在使用listagg()之前进行区分

dbfiddle

相关问题