将行数据转换为SQL Server中的列

时间:2019-05-06 22:08:10

标签: sql sql-server sql-server-2014

我有一张表格,其中的数据格式如下。

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

我需要将此表导出为以下格式:单个用户的所有记录都应放在一行中,付款日期和金额记录应从左开始,从最早的记录开始。

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条记录,则这些列将保留为空。

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

1 个答案:

答案 0 :(得分:1)

您可以使用条件聚合:

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;