SQL Server - 如何选择带有单词 "Rehired" 的第一行,该行显示在最后一行之后,带有单词 "Quit"


Date..............Comment1............................Comment2
20041206.....Address change from/to:........616 Barry Road Apt
20050314.....Rehired on Mar 14/05............Rehired on Mar 14/05
20051117.....Terminated on Nov17/05.......Shortage of Work
20060131.....Address change from/to:........616 Barry Road Apt
20060410.....Rehired on Apr 10/06   ............Pay Rate change    
20060419.....Vac. pay owing: from..............changed by 
20060531.....Terminated on May31/06........Quit
20070208.....Address change from/to:........11 Bettley Court
20080921.....Rehired on Sep 21/08............Pay Rate change    <== this row
20080925.....Vac. pay owing:.....................from   
20090215.....Pay Rate change...................0.00
20090712.....Pay Rate change...................0.000

我想以指定记录中的日期 (20080921) 结束。

类似

SELECT TOP 1 *
FROM   YourTable
WHERE  Date > (SELECT TOP 1 Date
               FROM   YourTable
               WHERE  ( Comment1 LIKE '%Quit%'
                         OR Comment2 LIKE '%Quit%' )
               ORDER  BY Date DESC)
       AND ( Comment1 LIKE '%Rehired%'
              OR Comment2 LIKE '%Rehired%' )
ORDER  BY Date 

有点粗糙,但是:

SELECT t2.DATE
FROM TABLE t1 INNER JOIN
     TABLE t2 on t1.Date < t2.Date LEFT OUTER JOIN
     TABLE t3 on t1.Date < t3.Date AND t3.Date < t2.Date AND t3.Comment1 LIKE 'Rehired%' LEFT OUTER JOIN
     TABLE t4 on t4.Date > t1.Date and t4.Comment2 = 'Quit'
WHERE t1.Comment2 = 'Quit'
AND t2.Comment1 like 'Rehired%'
AND t3.Date = null
AND t4.Date = null

T1 是您的辞职记录,T2 是您重新雇用的记录。 T3 确保在 T1 和 T2 之间不会发生其他重新雇用,T4 确保在 T1 之后不会发生其他退出。 因此,t2 是最后一个辞职后第一个重新雇用的人。

日期格式可能很棘手,但请尝试这样做。

declare @LastDate datetime
set @LastDate='2008/09/21'
select date,comment1,comment2 from your table 
where cast(date as datetime)>=@LastDate 
order by date

最新更新