根据每列中定义的月份和年份,从一个 table 另一列插入一列作为一行

Insert a column from one table another as a row based on months and years defined in each column

我有一个 table,我需要以某种方式将 table 中的数据插入另一个空白 table。

Year LoanType ProcessDate Month Balance RowNum TypeRow PercentChange LastCol
2022 0 20220430 04 500 1 1 -1.22 450
2022 0 20220331 03 450 2 2 1.01 200
2022 0 20220228 02 200 3 3 -.012 600
2022 0 20220128 01 200 4 4 -.012 600
2022 0 20221228 12 200 5 5 -.012 600
2022 0 20211128 11 200 6 6 -.012 600
2022 0 20211028 10 200 7 7 -.012 600
2022 0 20210928 09 200 8 8 -.012 600
2022 0 20210828 08 200 9 9 -.012 600
2022 0 20210728 07 200 10 10 -.012 600
2022 0 20210628 06 200 11 11 -.012 600
2021 0 20210528 05 200 12 12 -.012 600
2021 0 20210428 04 200 13 13 -.012 600
2022 1 20220430 04 500 1 1 -1.22 450
2022 1 20220331 03 450 2 2 1.01 200
2022 1 20220228 02 200 3 3 -.012 600
2022 1 20220128 01 200 4 4 -.012 600
2022 1 20221228 12 200 5 5 -.012 600
2022 1 20211128 11 200 6 6 -.012 600
2022 1 20211028 10 200 7 7 -.012 600
2022 1 20210928 09 200 8 8 -.012 600
2022 1 20210828 08 200 9 9 -.012 600
2022 1 20210728 07 200 10 10 -.012 600
2022 1 20210628 06 200 11 11 -.012 600
2021 1 20210528 05 200 12 12 -.012 600
2021 1 20210428 04 200 13 13 -.012 600

所以这里发生的是有不同的“贷款类型”

我要塞进去的table是这样的:

Year LoanType Jan Feb Mar April May June July Aug Sep Oct Nov Dec
2022 0 1.1 -2.5 5.1 .12
2021 0 1.1 -2.5 5.1 .12 .1 -1.22 4.50 -1.22 -1.22 -1.22 -1.22 -1.22
2022 1 1.1 -2.5 5.1 .12
2021 1 1.1 -2.5 5.1 .12 .1 -1.22 4.50 -1.22 -1.22 -1.22 -1.22 -1.22

所以我需要根据年份和贷款类型将每个 PercentChange 插入到它所属的位置,如上所示,仅使用随机数。

我尝试使用 case 语句在其中插入值,但它每隔一个月为每一行提供一个带有零的行。

select * from #LoanT
order by LoanType asc, RowNum asc

您可以使用条件聚合:

select year
     , loantype
     , jan = min(case when month = 1 then percentchange end)
     , ...
     , dec = min(case when month = 12 then percentchange end)
from loan
group by year, loantype