操縱排名的關鍵是使用聯合。對於每一列你使用一個單獨的select語句。在該語句中,添加一個標識符,該標識符顯示每行從哪個列被拉出。將結果插入到表變量中,然後可以通過對標識符進行排序操作排名,或者根據標識符將排名乘以某個值。
關鍵是給出修改排名的外觀,而不是實際改變sql server的排名。
例如使用表變量:
DECLARE @Results TABLE (PersonId Int, Rank Int, Source Int)
對於列PersonId Int PK Identity, FirstName VarChar(100), MiddleName VarChar(100), LastName VarChar(100), AlsoKnown VarChar(100)
每一列添加到全文目錄,您可以使用查詢表人物:
INSERT INTO @Results (PersonId, Rank, Source)
SELECT PersonId, Rank, 1
FROM ContainsTable(People, FirstName, @SearchValue) CT INNER JOIN People P ON CT.Key = P.PersonId
UNION
SELECT PersonId, Rank, 2
FROM ContainsTable(People, MiddleName, @SearchValue) CT INNER JOIN People P ON CT.Key = P.PersonId
UNION
SELECT PersonId, Rank, 3
FROM ContainsTable(People, LastName, @SearchValue) CT INNER JOIN People P ON CT.Key = P.PersonId
UNION
SELECT PersonId, Rank, 4
FROM ContainsTable(People, AlsoKnown, @SearchValue) CT INNER JOIN People P ON CT.Key = P.PersonId
/*
Now that the results from above are in the @Results table, you can manipulate the
rankings in one of several ways, the simplest is to pull the results ordered first by Source then by Rank. Of course you would probably join to the People table to pull the name fields.
*/
SELECT PersonId
FROM @Results
ORDER BY Source, Rank DESC
/*
A more complex manipulation would use a statement to multiply the ranking by a value above 1 (to increase rank) or less than 1 (to lower rank), then return results based on the new rank. This provides more fine tuning, since I could make first name 10% higher and middle name 15% lower and leave last name and also known the original value.
*/
SELECT PersonId, CASE Source WHEN 1 THEN Rank * 1.1 WHEN 2 THEN Rank * .9 ELSE Rank END AS NewRank FROM @Results
ORDER BY NewRank DESC
的一個缺點是你會注意到我沒有使用UNION ALL
,所以如果一個單詞出現在多個列中,排名不會反映出來。如果這是個問題,您可以使用UNION ALL
,然後通過將全部或部分重複記錄的等級添加到具有相同人員ID的另一記錄的等級中,刪除重複的人員ID。
這非常有幫助!這已經不是SQL Server的內容了,這真是令人遺憾。 – 2011-02-27 19:54:42