I have two tables in sql. One is a table of test cases and the other is a table of test runs with a foreign key that links back to a test case. I want to get the most recent 10 test runs for each test case. I don't want to loop through if I don't have to, but I don't see any other way to solve this problem. What is the most effective way to handle this sort of thing in sql server?
Asked
Active
Viewed 111 times
7
-
Abul and Roman thanks for the quick reply. I'm going to try both and let you know the results – Adam Carr May 08 '15 at 15:18
3 Answers
7
The idea:
select
...
from <test cases> as tc
outer apply (
select top 10 *
from <test runs> as tr
where
tr.<test case id> = tc.<id>
order by tr.<date time> desc
) as tr
or, if you just need to get data from table:
;with cte_test_runs as (
select
*,
row-Number() over(partition by <test case id> order by <date time> desc) as rn
from <test runs>
)
select *
from cte_test_runs
where rn <= 10

Roman Pekar
- 107,110
- 28
- 195
- 197
3
You can use Row No. Use Inner of Left Join as the case may be..
Select * from testCase a
left outer join
(Select Row_number() over (partition by testcase order by RecentDate desc ) RowNo, * from TestRuns) b
on a.pk = b.fk
where b.RowNo <=10

Abdul Rehman Sayed
- 6,532
- 7
- 45
- 74
1
You could use CROSS APPLY to select the top 10 per testCase ordered by date (or anyother ordering criteria).
See the related question 'When should I use Cross Apply over Inner Join?' which explains it better than I can. https://stackoverflow.com/a/1139231/1620715
In your case:
SELECT * from TestCase T
CROSS APPLY
( SELECT TOP 10 * from TestRuns R where T.TestCaseId = R.TestCaseId
order by R.TestDate desc) TopResults