返回列的最大值百分比内的行

时间:2011-10-06 11:33:11

标签: sql-server sql-server-2005 full-text-search

使用SQL Server 2005全文搜索我想在该搜索的最大相关结果的百分比内返回值。

 SELECT 
 A.ActivityID,
 KEY_TBL.Rank as Relevance, 
 DENSE_RANK() OVER (ORDER BY  Rank DESC) as SearchRank
 FROM Activity A 
 INNER JOIN FREETEXTTABLE(vwActivitySearch, FTS,'My search expression') AS KEY_TBL ON A.ActivityID = KEY_TBL.[KEY]

返回:

    ActivityID  Relevance   SearchRank
    ----------- ----------- --------------------
    89378       242         1
    89406       242         1
    88083       236         2
    88214       236         2
    84007       197         3
    83434       197         3
    13017       172         4
    89247       164         5
    89346       164         5

我不想按等级返回,而是返回大于最大相关性的90%或某个任意百分比的值,因此在此示例中

 WHERE Relevance>(242*0.9). 

我确信有一种简单的方法可以实现这一点,但我看不到它。

一些限制 -

  • 查询是UDF中的CTE表达式。
  • 我可以轻松运行初始查询以获取@ MAXRelevance = SELECT MAX(Relevance)...然后在WHERE子句中使用Max(Relevance),但全文搜索不保证为相关结果返回相同的绝对值重复搜索。

现有功能:

 CREATE FUNCTION [dbo].[xxActivitySearch] (@SearchTerm varchar(255)='',@ResultDepth int)
 RETURNS @ReturnTable Table (ActivityID int,Relevance int,SearchRank int)
 AS
 BEGIN
 WITH T AS (
 SELECT 
   A.ActivityID,
   KEY_TBL.Rank as Relevance, 
   DENSE_RANK() OVER (ORDER BY  Rank DESC) as SearchRank
 FROM Activity A 
INNER JOIN FREETEXTTABLE(vwActivitySearch, FTS,@SearchTerm) AS KEY_TBL ON A.ActivityID=KEY_TBL.[KEY])
INSERT @ReturnTable SELECT * FROM T WHERE (SearchRank<=@ResultDepth)
RETURN
END 

1 个答案:

答案 0 :(得分:2)

WITH T AS
(
SELECT A.ActivityID,
       KEY_TBL.Rank                           as Relevance,
       DENSE_RANK() OVER (ORDER BY Rank DESC) as SearchRank,
       MAX(KEY_TBL.Rank) OVER() AS MaxRelevance
FROM   Activity A
       INNER JOIN 
         FREETEXTTABLE(vwActivitySearch, FTS, 'My search expression') AS KEY_TBL
         ON A.ActivityID = KEY_TBL.[KEY]  

)
SELECT ActivityID,
       Relevance,
       SearchRank
FROM T
WHERE Relevance>(MaxRelevance*0.9)