0

我想在此表中添加另一列,如果第一期的模式是“现金”,第二期的模式是“电子”,则在 PersonID 前面会显示“现金到电子”。

PersonID    InstalmentNumber  DateOfInstalment          Mode
50023467    2                   15-Mar-12               Electronic
50023467    1                   15-Feb-12               Electronic
50023468    2                   5-Apr-12                Cash
50023468    1                   5-Mar-12                Cash
50023469    2                   15-Mar-12               Electronic
50023469    2                   15-Mar-12               Electronic
50023469    1                   15-Feb-12               Electronic
50023469    1                   15-Feb-12               Cash
50027967    2                   15-Mar-12               Electronic

预期输出:

PersonID    InstalmentNumber  DateOfInstalment          Mode           Flag
50023467    2                   15-Mar-12               Electronic    
50023467    1                   15-Feb-12               Electronic
50023468    2                   5-Apr-12                Cash
50023468    1                   5-Mar-12                Cash
50023469    2                   15-Mar-12               Electronic
50023469    2                   15-Mar-12               Electronic
50023469    1                   15-Feb-12               Cash
50023469    1                   15-Feb-12               Cash           Cash To Electronic
50027967    2                   15-Mar-12               Electronic
4

2 回答 2

2

试试这个方法:

select distinct t.PersonID,t.InstalmentNumber,t.DateOfInstalment,t.Mode, 
       case 
          when x.PersonID is not null
             and t.Mode = 'Cash'
             and t.InstalmentNumber = 1
            then 'Cash to Electronic'
          else null
       end as Flag
from tab t
left join tab x on x.PersonID = t.PersonID AND
                   x.Mode = 'Electronic' AND
                   x.InstalmentNumber = 2

Sql 小提琴演示

于 2013-07-29T13:08:50.703 回答
0

可能迟到了,但我会使用窗口函数

select
    distinct PersonID,
    InstalmentNumber,
    DateOfInstalment,
    Mode,
    case
        when lead(Mode) over(partition by PersonID order by InstalmentNumber) = 'Cash' then 'Cash to Electronic'
        else null
    end as Flag
from tab
于 2018-11-22T17:22:16.017 回答