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

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

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

  1. ID | Preference| Destination
  2. --------------------------
  3. 10 | 1 | Building A
  4. 10 | 2 | Building B
  5. 10 | 3 | Building C
  6. 23 | 1 | Building B
  7. 23 | 2 | Building A
  8. 45 | 1 | Building C

表b

  1. ID | Destination1 | Destination2 | Destination3
  2. -----------------------------------------------
  3. | | |

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

  1. ID | Destination1 | Destination2 | Destination3
  2. -----------------------------------------------
  3. 10 | Building A | Building B | Building C
  4. 23 | Building B | Building A | NULL
  5. 45 | Building C | NULL | NULL

非常感谢您的帮助!

mzillmmw

mzillmmw1#

可以使用条件聚合:

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

相关问题