我有一个 table1,我想将其转换为预期的表格。
- 列的预期表逻辑:
- cal:来自table1的cal。ID 来自 table1 的 ID。
- 代码:这取决于我们在 f_a 中是否有一个值,然后我们用 fp 作为代码创建一个新记录。与它相对应,我们检查是否填充了 f_a,如果是,则我们从 f_a 中获取该日期并放入同一 ID 的 Al 列中。我们还检查是否填充了 f_pl,如果是,则我们从中获取日期并将其放在 pl 列中。
- 如果代码是 lp,那么我们检查是否填充了 l_a,然后我们取该日期并将该日期放在 Al 中,以获取该代码和 Id。此外,我们检查是否填充了 lpl,如果是,则我们取该日期并将其放入 pl。
我只是 SQL 的初学者,所以对于如何开始它对我来说有点不知所措。请发布一些解决方案。
表格1:
ID f_a l_a f_pl lpl cal
CNT 6/20/2018 6/28/2018 6/28/2018 1/31/2020
预期输出:
ID Cal code pl Al
CNT 1/31/2020 lp 6/28/2018 6/28/2018
CNT 1/31/2020 fp 6/20/2018
更新:我在表中有更多的 ID,所以不是 CNT 是唯一的 ID。如果我使用 unpivot,那么它应该对所有 ID 遵循相同的逻辑。