使用row_num()并在WHERE CLAUSE查询中使用来自窗口函数的过滤值

时间:2017-08-07 12:03:58

标签: sql sql-server where-clause window-functions row-number

我有存储过程.SELECT语句如下所示

select  
*, row_number() OVER (ORDER BY ProductRN.ID) as RNN
from  (
SELECT 

p.ID
,p.ProductCode
,p.ProductNameF
,p.ProductNameE
,p.[Weight]
,p.PackageTypeID
,p.ISForeign
,p.BrandID
,b.BrandNameF
,b.BrandNameE
,p.ImgID
,p.CategoryID
,p.AmountInBox
,pc.PropertyGroupID
,p.Comment
,p.CompanyID
,p.Status
,po.CompanyNameF
,PriceConsumer=MKT.Fn_GetProductPrice(1,p.ID, @CurDate)
,PriceRetail=MKT.Fn_GetProductPrice(2,p.ID, @CurDate)
,PriceWholesale=MKT.Fn_GetProductPrice(3,p.ID, @CurDate)
,pg.PropertyName as PropertyGroupName
,b.LogoID
from mkt.Product as p (nolock)
inner join mkt.ProductCategory as pc (nolock) on pc.ID = p.CategoryID
inner join mkt.Brand b (nolock) on p.BrandID=b.ID
inner join MKT.ProductOwner as po (nolock) on po.ID = b.BrandOwnerID
left  join MKT.PropertyGroup as pg (nolock) on pc.PropertyGroupID=pg.ID

) AS  ProductRN 

where ProductRN.CompanyID=@CompanyID 
and  ProductRN.Status=1 
and  ProductRN.CategoryID=@ProductCategoryID
AND  (ProductRN.BrandID=@BrandID OR @BrandID=0)
--SOME WAY TO FILTER RNN

end

在WHERE CLAUSE中没有任何方法可以使用RNN列,因为我们无法在WHERE CLAUSE中使用列别名和窗口函数。 实际上问题是,当我把

row_number() OVER (ORDER BY ProductRN.ID) as RNN 

在内部SELECT语句中,RNN列完全等于p.ID(Product.ID)似乎sql server首先计算row_number()然后执行WHERE CLAUSE。

如何更改此查询,以便row_num()应用于最终查询记录 我可以在WHERE CLAUSE中过滤它。

1 个答案:

答案 0 :(得分:4)

使用子查询或CTE:

select t.*
from (<your query goes here>) t
where rnn = 1;