如何将两行转换为一行作为先行记录和当前记录

时间:2019-05-22 14:47:43

标签: sql sql-server tsql

我有一张桌子,里面有以下数据。

Batch      Ingredient       Transaction date
----   -----------------  --------------------
A              I1              2019/05/22
A              I2              2019/05/23
A              I3              2019/05/24

我想按以下格式按交易日期显示最多两个记录

Batch      Ingredient1     TransDate1    Ingredient2     TransacDate2
----    ---------------- ------------- ---------------- --------------    
A              I3          2019/05/24        I2           2019/05/23

成分1应该是最新记录,并且成分是前一个记录。没有成分3。

我尝试了数据透视表,但是没有用。

1 个答案:

答案 0 :(得分:1)

您可以使用row_number()和条件聚合:

select batch,
       max(case when seqnum = 1 then ingredient end) as ingredient1,
       max(case when seqnum = 1 then transdate end) as transdate1,
       max(case when seqnum = 2 then ingredient end) as ingredient2,
       max(case when seqnum = 2 then transdate end) as transdate2
from (select t.*,
             row_number() over (partition by batch order by transdate desc) as seqnum
      from t
     ) t
where seqnum <= 2
group by batch;