将行数据转换为 SQL 服务器中的列

Transforming row data into columns in SQL Server

我有 table 以下格式的数据。

User ID| Date Paid  | Amount Paid
- - - - - - - - - - - - - - - - - 
1      | 2019-04-01 | 120
1      | 2019-03-01 | 120
1      | 2019-05-01 | 130
2      | 2019-03-01 | 100
2      | 2019-04-01 | 110
3      | 2019-05-01 | 100

我需要将此 table 导出为一种格式,其中单个用户的所有记录都应在一行中,并且支付日期和金额记录应从最旧的记录开始从左开始。

User ID | 1st Date Paid | 1st Amount Paid | 2nd Date Paid | 2nd Amount Paid | 3rd Date Paid | 3rd Amount Paid | . . . . . 
- - - - - - - -  - - - - - -  - - - -- - - - - - --  -- - -  -- - - - - - - - 
   1    | 2019-03-01    | 120             | 2019-04-01    | 120             | 2019-05-01 | 130
   2    | 2019-03-01    | 100             | 2019-40-01    | 110             |
   3    | 2019-05-01    | 100             |

每个用户最多可以有 10 条记录,因此导出应包含支付日期和支付金额列 10 次。如果用户不包含 10 条记录,则这些列将留空。

达到这个结果的最佳方法是什么?

您可以使用条件聚合:

select user_id,
       max(case when seqnum = 1 then date_paid end) as date_paid1,
       max(case when seqnum = 1 then amount_paid end) as amount_paid1,
       max(case when seqnum = 2 then date_paid end) as date_paid2,
       max(case when seqnum = 2 then amount_paid end) as amount_paid2,
       max(case when seqnum = 3 then date_paid end) as date_paid3,
       max(case when seqnum = 3 then amount_paid end) as amount_paid3
from (select t.*,
             row_number() over (partition by user_id order by date_paid) as seqnum
      from t
     ) t
group by user_id;