加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MsSql教程 > 正文

如何为sql server 2012中的另一个表中的每个父主键选择一个表的

发布时间:2020-12-12 07:05:13 所属栏目:MsSql教程 来源:网络整理
导读:我在sql中有两个表.一个是测试用例表,另一个是测试运行表,其中一个外键链接回测试用例.我想为每个测试用例获得最近10次测试运行.如果我不需要,我不想循环,但我没有看到任何其他方法来解决这个问题.在sql server中处理这类事情最有效的方法是什么? 解决方法
我在sql中有两个表.一个是测试用例表,另一个是测试运行表,其中一个外键链接回测试用例.我想为每个测试用例获得最近10次测试运行.如果我不需要,我不想循环,但我没有看到任何其他方法来解决这个问题.在sql server中处理这类事情最有效的方法是什么?

解决方法

想法:
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

或者,如果您只需要从表中获取数据:

;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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读