SQL Table 基于模式

SQL Table based on a pattern

我有一个 Table 喜欢:

source    target              
jan       feb                               
mar       apr                 
jun                       
feb       aug                                            
apr       jul                                            
oct       dec                     
aug       nov       
dec       may                               

输出(我想在其中创建一个 new_target 列):

source    target    new_target              
jan       feb       aug                        
mar       apr       jul                  
jun                              
feb       aug       nov                                     
apr       jul                                                  
oct       dec       may              
aug       nov       
dec       may      

目的是根据这样的逻辑创建 new_target 列 - 例如,源中的 jantarget 中具有值 feb。这反过来,源中的 febtarget 中具有值 aug,依此类推 augtarget 列中具有 nov 因此 new_target 列将具有第三个值:即(源和目标 jan->feb->aug->nov 之间的跟踪,因为 aug 是第三个值,它是 new_target 列中的输出)

这看起来像 left join:

select t.*, tnext.target
from t left join
     t tnext
     on t.target = t.next.source

试试这个:

select  m1.source, 
        m1.target, 
        m2.target as new_target
from mytable m1
left join mytable m2 on 
  m1.target = m2.source

left join 将保留原始 table 中的所有行,同时如果匹配,则将值添加到 new_target 列。