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

时间:2012-06-20 16:42:05

标签: sql-server-2000

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)。

3 个答案:

答案 0 :(得分:1)

这样的东西
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 

答案 1 :(得分:0)

有点粗糙,但是:

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是最后一次退出后最先重新雇用的。

答案 2 :(得分:0)

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

declare @LastDate datetime
set @LastDate='2008/09/21'

select date,comment1,comment2 from your table 
where cast(date as datetime)>=@LastDate 
order by date