标量函数上的 RANK() 帮助 - SQL Server 2008
我有以下内联表值函数:
SELECT Locations.LocationId,
dbo.Search_GetSuitability(@SearchPreferences,
Score.FieldA, Score.FieldB, Score.FieldC) AS OverallSuitabilityScore,
RANK() OVER (ORDER BY OverallSuitabilityScore) AS OverallSuitabilityRank
FROM dbo.LocationsView Locations
INNER JOIN dbo.LocationScores Score ON Locations.LocationId = Score.LocationId
WHERE Locations.CityId = @LocationId
RANK()
行给了我一个错误:
列名称“OverallSuitabilityScore”无效。
函数 dbo.Search_GetSuitability
是一个标量函数,它返回 DECIMAL(8,5)
。我需要根据该值为每一行分配一个排名。
我可以让上述工作的唯一方法是再次在 ORDER BY
部分添加标量函数调用 - 这是愚蠢的。我有大约 5 个标量函数调用,每个调用都需要单独的 RANK() 值。
我能做些什么?我可以使用通用表表达式 (CTE) 吗?
I have the following Inline Table-Valued Function:
SELECT Locations.LocationId,
dbo.Search_GetSuitability(@SearchPreferences,
Score.FieldA, Score.FieldB, Score.FieldC) AS OverallSuitabilityScore,
RANK() OVER (ORDER BY OverallSuitabilityScore) AS OverallSuitabilityRank
FROM dbo.LocationsView Locations
INNER JOIN dbo.LocationScores Score ON Locations.LocationId = Score.LocationId
WHERE Locations.CityId = @LocationId
That RANK()
line is giving me an error:
Invalid column name 'OverallSuitabilityScore'.
The function dbo.Search_GetSuitability
is a scalar-function which returns a DECIMAL(8,5)
. I need to assign a rank to each row based on that value.
The only way i can get the above to work is to add the scalar function call in the ORDER BY
part again - which is silly. I have about 5 of these scalar function calls and i need seperate RANK()
values for each.
What can i do? Can i use a Common Table Expression (CTE) ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,您不能在 SELECT 子句中引用列别名。不过 CTE 听起来不错。这是一个例子
Yep, you can't reference a column alias in the SELECT clause. The CTE sounds good though. Here's an example
执行此操作的一种老式方法就是对表达式进行 SUBQUERY。
这里的CTE只是将子查询移到顶部
An old school way of doing this is just to SUBQUERY the expression.
The CTE here only moves the subquery to the top