SQL - 最新行的自联接

时间:2012-12-16 03:49:04

标签: sql

这是表格:

    id -           date               - attempts
    --------------------------------------------
    1  -  2012-12-11 14:52:06.143     - success
    2  -  2012-12-11 15:51:52.320     - whatever
    3  -  2012-12-11 12:51:52.321     - success
    4  -  2012-12-11 12:51:52.312     - whatever 
    5  -  2012-12-11 14:51:52.320     - fail

我正在尝试获取最新的“失败”和最新的“成功”行,然后在两者中查看最新的行是否失败(可能会有成功的行晚于失败行)。

我不能只选择最新的行,因为它可能不是“成功”或“失败”。

2 个答案:

答案 0 :(得分:4)

内部查询将识别具有成功或失败尝试的最新日期的记录,外部查询与内部查询的结果相结合以识别失败记录。

SELECT
    a.*
FROM
    myTable a
    JOIN
    (
        SELECT MAX(date) AS `date` FROM myTable
        WHERE attempts IN ('success', 'fail')
    ) b
    ON a.date = b.date
WHERE
    a.attempts = 'fail'

答案 1 :(得分:0)

  Select s.id successId, s.date latestSuccess, 
         f.id failId, f.date latestFail, 
         case When s.date > f.Date 
              Then 'Success' Else 'Fail' End Last
  From myTable s full join mytable f
     On s.attempts = 'success'
        And s.date - (Select Max(date) From myTable
                    Where attempts = 'success')
        And f.attempts = 'fail'
        And f.date - (Select Max(date) From myTable
                      Where attempts = 'fail')