sql查询首先处理最高计数

时间:2014-07-17 08:53:26

标签: sql sql-server

我的sql查询问题如下:

select * from Assignment as a 
inner join #resource as r 
    on a.ResourceID = r.ResourceID
inner join Resource as pr 
   on pr.ResourceID = r.ResourceID
inner join #workitem as uw 
   on uw.ReferenceID = pr.ResourceSecurityUserID
where uw.WorkQueueID = some id here
   and uw.WorkStatusID = some status id here

它的作用是使用临时表#resource中的id获取Assignment表中资源的所有赋值,并查看Resource表并使用#workitem表中的referenceid。

#workitem临时表的目的是对我的所有进程进行排队。这是我的要求。是否有可能我只想从#workitem临时表中top 100,以便首先处理前100名。

提前致谢。

2 个答案:

答案 0 :(得分:1)

您可以尝试这样的事情: -

SELECT * FROM Assignment AS a 
INNER JOIN #resource AS r ON a.ResourceID = r.ResourceID
INNER JOIN Resource AS pr ON pr.ResourceID = r.ResourceID
INNER JOIN (SELECT TOP 100 * FROM #workitem) as uw ON uw.ReferenceID = pr.ResourceSecurityUserID
WHERE uw.WorkQueueID = some id here
AND uw.WorkStatusID = some status id here

希望这会对您有所帮助。

答案 1 :(得分:1)

当您加入工作项临时表时,将其作为内部联接,并在其中生成row_number,以便您可以限制加入的记录数。

select * from Assignment as a 
inner join #resource as r 
    on a.ResourceID = r.ResourceID
inner join Resource as pr 
   on pr.ResourceID = r.ResourceID
inner join (
  select *, row_number() over () as rn
  from #workitem uw
) as uw on uw.ReferenceID = pr.ResourceSecurityUserID and uw.rn <= 100
where uw.WorkQueueID = some id here
   and uw.WorkStatusID = some status id here