Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I select a given number of rows for one table for each parent primary key in another table in sql server 2012?

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?

like image 464
Adam Carr Avatar asked May 08 '15 14:05

Adam Carr


People also ask

How do you use a composite primary key?

A composite key is made by the combination of two or more columns in a table that can be used to uniquely identify each row in the table when the columns are combined uniqueness of a row is guaranteed, but when it is taken individually it does not guarantee uniqueness, or it can also be understood as a primary key made ...

How can we find primary key and foreign key relationship in SQL?

If we want to know the table's primary keys and foreign keys. We can simply use an “information_schema. key_column_usage” view, this view will return all of the table's foreign keys and primary keys.

How many primary keys can have in a table a only 1?

The PRIMARY KEY constraint uniquely identifies each record in a table. Primary keys must contain UNIQUE values, and cannot contain NULL values. A table can have only ONE primary key; and in the table, this primary key can consist of single or multiple columns (fields).


1 Answers

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
like image 110
Roman Pekar Avatar answered Sep 22 '22 02:09

Roman Pekar