sql—将数量可变的记录组合成单个记录

pkln4tw6  于 2021-07-29  发布在  Java
关注(0)|答案(1)|浏览(247)

问题的要点是,我需要基于一个共享id将表a中的多个记录合并到一个记录中,并将其插入表b中。每个id最多可以有三条与之关联的记录,最少1条,这是该id的首选目的地。如果该记录的首选项数小于最大值,我希望在表b中将这些列设置为null。
举个例子:
表a

ID | Preference| Destination
--------------------------
10 | 1         | Building A
10 | 2         | Building B
10 | 3         | Building C
23 | 1         | Building B
23 | 2         | Building A
45 | 1         | Building C

表b

ID | Destination1 | Destination2 | Destination3
-----------------------------------------------
   |              |              |

我想合并表a中的记录,以便它在表b中显示为这样

ID | Destination1 | Destination2 | Destination3
-----------------------------------------------
10 | Building A   | Building B   | Building C   
23 | Building B   | Building A   | NULL    
45 | Building C   | NULL         | NULL

非常感谢您的帮助!

mzillmmw

mzillmmw1#

可以使用条件聚合:

select id,
       max(case when preference = 1 then destination end) as destination1,
       max(case when preference = 2 then destination end) as destination2,
       max(case when preference = 3 then destination end) as destination3
from t
group by id;

相关问题