SELECT TOP N带变量

时间:2012-09-27 07:13:02

标签: sql sql-server-2008

我在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 个答案:

答案 0 :(得分: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

答案 1 :(得分:2)

尝试:

declare @RndQuesnCount int;

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

set rowcount @RndQuesnCount;

select * from QuesTable;

答案 2 :(得分: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

答案 3 :(得分:0)

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

SQLServer SQL query with a row counter