SQL选择将事务行转换为列

时间:2015-03-14 15:03:02

标签: tsql sql-server-2008-r2 pivot greatest-n-per-group

我有一个列出所有交易的表格如下:

ID  Account Date    Amount
---------------------------
1   2   02/01/2015  30
2   5   05/01/2015  25
3   2   05/01/2015  12
4   2   07/01/2015  42
5   5   10/012015   19
6   2   11/01/2015  58
7   3   15/01/2015  36

想写一个select语句,只列出每个帐户的最后3个交易,如下所示。

Account Date1   Amount      Date2   Amount      Date3   Amount
---------------------------------------------------------------
2       11/01/2015  58      07/01/2015  42      05/01/2015  12
3       15/01/2015  36              
5       10/01/2015  19      05/01/2015  25      

感谢您的任何建议

1 个答案:

答案 0 :(得分:0)

您可以使用派生表中的row_number()函数按帐户对数据进行分区,并为分区中的每个日期指定一个数字,然后对具有前3个数字的行进行条件聚合,分组按帐户:

select 
    account,
    date1  = max(case when rn = 1 then date   end),
    amount = max(case when rn = 1 then amount end),
    date2  = max(case when rn = 2 then date   end),
    amount = max(case when rn = 2 then amount end),
    date3  = max(case when rn = 3 then date   end),
    amount = max(case when rn = 3 then amount end)
from (
    select *, rn = row_number() over (partition by account order by date desc) 
    from your_table
) a
where rn <= 3
group by account

Sample SQL Fiddle