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

sql – 具有变量的SELECT TOP N

发布时间:2020-12-12 08:50:09 所属栏目:MsSql教程 来源:网络整理
导读:我在SQL表中有以下数据 Temp表变量@RndQuesnCount包含这个数据, Recid conceptID MinDisplayCount1 3839 22 4802 3 问题表:QuesTable QuesCompID Ques_ConceptDtlID 88 4802 89 4802 90 4802 91 4802 92 4802 93 4802 我想显示的是对于概念id在@RndQuesnCoun
我在SQL表中有以下数据

Temp表变量@RndQuesnCount包含这个数据,

Recid conceptID MinDisplayCount
1      3839     2
2      4802     3

问题表:QuesTable

QuesCompID     Ques_ConceptDtlID
  88         4802
  89         4802
  90         4802
  91         4802
  92         4802
  93         4802

我想显示的是对于概念id在@RndQuesnCount中的问题的最小显示数,所以现在的数据应该如下

QuesCompID    Ques_ConceptDtlID
  88         4802
  89         4802
  90         4802

因为conceptID(4802)在@RndQuesnCount表中具有最小显示数3.

任何人都可以帮我解决这个问题吗?

解决方法

我想,使用ROW_NUMBER()和一个join可以获得结果.数据设置:
declare @RndQuesnCount table (recid int,conceptid int,mindisplaycount int)
insert into @RndQuesnCount(Recid,conceptID,MinDisplayCount) values
(1,3839,2),(2,4802,3)

declare @QuesTable table (QuesCompID int,Ques_ConceptDtlID int)
insert into @QuesTable(QuesCompID,Ques_ConceptDtlID) values
(88,4802),(89,(90,(91,(92,(93,4802)

查询:

select
    t.rn,t.QuesCompID,t.Ques_ConceptDtlID 
from
    @RndQuesnCount rqc
        inner join
    (select *,ROW_NUMBER() OVER (PARTITION BY Ques_ConceptDtlID ORDER BY QuesCompID) rn from @QuesTable) t
        on
            rqc.conceptID = t.Ques_ConceptDtlID and
            rqc.MinDisplayCount >= t.rn

结果:

rn                   QuesCompID  Ques_ConceptDtlID
-------------------- ----------- -----------------
1                    88          4802
2                    89          4802
3                    90          4802

(编辑:李大同)

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

    推荐文章
      热点阅读