按特定条件(复杂)排序查询结果

时间:2012-10-10 11:09:38

标签: sql sql-server tsql

思考是按短语获取搜索结果(搜索多个列),排序优先级必须取决于匹配的列(包括完全匹配的情况)。

我的示例运行正常,但我仍然认为有更好的方法:

WITH    products
  AS ( SELECT
        -- .. some columns
        --------- For Sorting -------------
        [sortOrder] = CASE 
            WHEN [partNumber] = @searchPhrase                                                                       
             OR [manPartNumber]= @searchPhrase
            THEN 1                                                                
            WHEN  FormatSiteNameForSearch( [siteName] ) 
                  LIKE '%' + @searchPhrase + '%'
            THEN 2                                                                        
            WHEN [partNumber] LIKE '%' + @searchPhrase + '%'
                 OR [manPartNumber] LIKE '%' + @searchPhrase + '%'
            THEN 3
            ELSE 100
            END
        --------- End For Sorting -------------
        FROM [dbo].[PRODUCTS_Products]           
        WHERE                                                                                                                            
            [partNumber] LIKE '%' + @searchPhrase + '%'
            OR [manPartNumber] LIKE '%'+ @searchPhrase + '%'
            OR FormatSiteNameForSearch([siteName]) LIKE '%'+@searchPhrase+'%'                                                              
            OR [name] LIKE '%'+ @searchPhrase+ '%'                                                                                                                      
    )
    SELECT TOP(10) *
    FROM    products
    ORDER BY sortOrder

谢谢。

1 个答案:

答案 0 :(得分:2)

SELECT TOP (10) * 
FROM   [dbo].[PRODUCTS_PRODUCTS] 
WHERE  [PARTNUMBER] LIKE '%' + @searchPhrase + '%' 
        OR [MANPARTNUMBER] LIKE '%' + @searchPhrase + '%' 
        OR Formatsitenameforsearch([SITENAME]) LIKE '%' + @searchPhrase + '%' 
ORDER  BY CASE 
            WHEN [PARTNUMBER] = @searchPhrase 
                  OR [MANPARTNUMBER] = @searchPhrase THEN 1 
            WHEN Formatsitenameforsearch([SITENAME]) LIKE 
                 '%' + @searchPhrase + '%' THEN 2 
            WHEN [PARTNUMBER] LIKE '%' + @searchPhrase + '%' 
                  OR [MANPARTNUMBER] LIKE '%' + @searchPhrase + '%' THEN 3 
            ELSE 100 
          END