有条件地在列之间移动值

Conditionally move values between columns

我有以下记录集输出:

   ID     Name          Pay_Type    Paid_Amnt    Interest_Amnt
   1     John Smith      Benefit      1075            0
   1     John Smith      Interest      1.23           0
   2     Tom Ryder       Benefit      1123            0
   3     Mark Thompson   Benefit      1211            0
   3     Mark Thompson   Interest     1.34            0

我想要的是将具有 Pay_Type = Interest 的值放在 Interest 列中。

期望的输出:

   ID    Name           Pay_Type    Pay_Type 2      Paid_Amnt   Interest_Amnt
    1    John Smith       Benefit     Interest        1075      1.23
    2    Tom Ryder        Benefit       NULL          1123        0
    3    Mark Thompson    Benefit      Interest       1211       1.34

我尝试了如下操作:

   Select row_number()over(partition by id, case when pay_type = 'Interest' then interest_amnt = paid_amnt
                                                 when pay_type = 'Interest' then paid_amnt = 0 end) as new_interest

有谁知道如何得到想要的结果?

谢谢

   declare @t table(id int, pay_type varchar(25), name varchar(100),  paid_amnt float, interest_amnt float)

   insert into @t values(1, 'Benefit', 'John Smith', 1075, 0),
                 (1, 'Interest', 'John Smith',1.23, 0),
                 (2, 'Benefit', 'Tom Ryder', 1123, 0),
                 (3, 'Benefit', 'Mark Thompson', 1211, 0),
                 (4, 'Interest', 'Mark Thompson', 1.34, 0)

    select * from @t

以防万一每个人可以拥有超过 2 条记录,我相信这会满足您的需求,它使用了几个子查询和分组依据,

子查询 x 对您的记录进行分组,以便您连续获得每个用户的利息总额和收益总额,

子查询 y 使用 CASE 表达式将总金额放入适当的列中,如果是 Benefit/Interest 则为零并添加支付类型pay_type1 和 pay_type2 的列分别具有 Benefit 和 Interest 的值,

外部查询 将所有内容分组为每个用户 1 行,并分别对他们的兴趣和收益列求和:

SELECT y.[id] AS [ID], y.[name] AS [Name], 
       y.[pay_type1] AS [Pay_Type], y.[Pay_Type2], SUM(y.[Paid_Amnt]) AS [Paid_Amnt], 
       SUM(y.[Interest_Amnt]) AS [Interest_Amnt]
FROM
(
    SELECT id, name, 'Benefit' AS [pay_type1], 'Interest' AS [pay_type2],
           CASE WHEN pay_type = 'Benefit' THEN x.Amount ELSE 0 END AS [Paid_Amnt], 
           CASE WHEN pay_type = 'Interest' THEN x.Amount ELSE 0 END AS [Interest_Amnt] 
    FROM
    (
        SELECT id, pay_type, name, SUM(paid_amnt) AS [Amount]
        FROM table as t
        GROUP BY id, pay_type, name
    ) AS x
) AS y
GROUP BY y.[id], y.[name], y.[pay_type1], y.[pay_type2]