11

我在 SQL 表中有以下数据

临时表变量@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

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

  QuesCompID    Ques_ConceptDtlID
  88         4802
  89         4802
  90         4802

因为conceptid(4802) 在@RndQuesnCount表中的最小显示计数为 3。

谁能帮我解决这个问题?

4

4 回答 4

8

我认为,简单的使用ROW_NUMBER()和连接就可以得到结果。数据设置:

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,         4802),
(90,         4802),
(91,         4802),
(92,         4802),
(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
于 2012-09-27T07:23:21.483 回答
2

尝试:

declare @RndQuesnCount int;

select @RndQuesnCount=MinDisplayCount 
from table_variable where conceptID=4802;

set rowcount @RndQuesnCount;

select * from QuesTable;
于 2012-09-27T07:17:14.000 回答
2

试试这个:

 ;WITH  cte as
     (  select *,row_number() over(order by QuesCompID) as row_num
        from   QuesTable   
        join   @RndQuesnCount
        on     Ques_ConceptDtlID=conceptID)
 SELECT QuesCompID,Ques_ConceptDtlID  
 FROM   cte 
 WHERE  row_num<=MinDisplayCount

结果:

QuesCompID    Ques_ConceptDtlID
88               4802
89               4802
90               4802
于 2012-09-27T07:24:02.230 回答
0

您可以将计数器列添加到查询结果并仅获取计数器小于或等于 MinDisplayCount 的行。

带有行计数器的 SQLServer SQL 查询

于 2012-09-27T07:24:17.330 回答