SQL查询具有不同时间戳的相同id的多个实例

时间:2013-01-11 17:02:10

标签: sql sql-server-2008

我有这个代表测试用例执行的表,对于一个特定的测试用例,可能有许多具有不同状态的执行。

id  |  testcase_id  |  status   |  timestamp
-------------------------------------------------------
1   |  2            |  fail     |  2013-01-11 15:00:00
-------------------------------------------------------
2   |  2            |  pass     |  2013-01-11 15:05:00
-------------------------------------------------------
3   |  4            |  fail     |  2013-01-11 16:00:00
-------------------------------------------------------
4   |  4            |  pass     |  2013-01-11 16:04:00

我想从这张表中提取的是最新的执行结果,即:

id  |  testcase_id  |  status   |  timestamp
-------------------------------------------------------
2   |  2            |  pass     |  2013-01-11 15:05:00
-------------------------------------------------------
4   |  4            |  pass     |  2013-01-11 16:04:00

我怎么能实现这个?

3 个答案:

答案 0 :(得分:1)

SELECT id,testcase_id,status,timestamp
FROM 
    (
        SELECT id,testcase_id,status,timestamp,
                ROW_NUMBER() OVER (PARTITION BY testcase_id
                                    ORDER BY timestamp DESC) rn
        FROM tableName
    ) s
WHERE Rn = 1

WITH latestRecord
AS
(
  SELECT id,testcase_id,status,timestamp,
  ROW_NUMBER() OVER (PARTITION BY testcase_id ORDER BY timestamp DESC) rn
  FROM tableName
) 
SELECT id,testcase_id,status,timestamp
FROM latestRecord
WHERE Rn = 1

答案 1 :(得分:0)

select tc.*
from testcases tc
inner join (
     select testcase_id,
     max(timestamp) maxTimestamp
     from testcases
     group by testcase_id
     ) tcMaxes
on tc.testcase_id = tcMaxes.testcase_id 
and tc.timestamp = tcMaxes.maxTimestamp

答案 2 :(得分:0)

试试这个

select top 2* from TableName where status='pass' order by timestamp asc

输出:http://sqlfiddle.com/#!3/1c810/38/0