限制从union query-SQL返回的行的最有效方法

时间:2010-12-23 13:46:22

标签: sql sql-server tsql sql-server-2008

嘿伙计......我有一个简单的存储过程,有两个查询与一个联合

加入
select name as 'result'
from product
where...

union

select productNum as 'result'
from product
where...

我想将此限制在TOP 10的结果......

如果我在每个单独的查询中输入TOP 10,我总共得到20个结果。

将总结果限制为10的最有效方法是什么?我不想在每个中做5个,因为我可能最终会遇到7个“名字”和3个“产品数”的情况

5 个答案:

答案 0 :(得分:12)

WITH Results (Result)
AS
(

select name as 'result'
from product
where...

union

select productNum as 'result'
from product
where...
)

SELECT TOP 10 * FROM Results

Common Table Expression

答案 1 :(得分:5)

select top 10 * from
(
select top 10 ....
from ....
where ....

union

select top 10 ....
from ....
where ....
) x

是基本的想法。将前10个添加到每个联合意味着您将在外部查询中设置一个较小的限制集。

如果您想优先排序(即从第一个结果中尽可能多地返回),那么您可以这样做:

select top 10 * from
(
select top 10 
1 as prio_col, ....
from ....
where ....

union

select top 10 
2 as prio_col....
from ....
where ....
) x
order by prio_col

这样你就可以从第一组得到尽可能多的东西,并且只使用第二组的结果作为“后备”。

答案 2 :(得分:3)

对每个子集使用top,最后使用它作为union结果。

select top 10 * from (
select top 10 name as 'result'
from product
where...

union

select top 10 productNum as 'result'
from product
where...
)

答案 3 :(得分:0)

您可以使用Sub QueryCommon Table Expression这样包装:

;with cte as 
(select name as 'result'
from product
where...

union

select productNum as 'result'
from product
where...) 
select top 10 * from cte;

答案 4 :(得分:0)

最简单的选择就是将Rowcount设置为10

Set RowCount 10
select name as 'result'
from product
where...

union

select productNum as 'result'
from product
where...