简体   繁体   English

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

[英]Transforming row data into columns in SQL Server

I have table with the data in following format. 我有以下格式的数据表。

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

I need export this table into a format where all of the records for a single user should be in a single row, and date paid and amount records should start from left with the oldest record first. 我需要将此表导出为一种格式,其中单个用户的所有记录都应放在一行中,并且付款日期和金额记录应从左开始,从最早的记录开始。

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             |

There could be up to a maximum of 10 records per user, so the export should contain the date paid and amount paid columns 10 times. 每个用户最多可以有10条记录,因此导出应包含10次付款日期和付款金额列。 If a user doesn't contain 10 records, then those columns will be left empty. 如果用户不包含10条记录,则这些列将保留为空。

What is the best way to achieve this result? 实现此结果的最佳方法是什么?

You can use conditional aggregation: 您可以使用条件聚合:

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM