开发者

Order by based on entered Keyword

I am facing problem in order by, I am fetching the records from SQL DB based on the keyword with like, now I want all records should be return bas开发者_如何学编程ed on entered keyword order. Example: If user enter "Physics" then it first return the Physics(exact word) if exists, after that return all another records.

SELECT *
FROM Subject SM
WHERE SM.SubjectName LIKE '%' + @SubjectName + '%'
ORDER BY @SubjectName DESC

How can I achieve this?


SELECT  *
FROM    Subject SM
WHERE   SM.SubjectName LIKE '%' + @SubjectName + '%'
ORDER BY CASE WHEN SM.SubjectName = @SubjectName THEN 0
              ELSE 1
         END ASC ,
        SM.SubjectName DESC


you can add more relevance:

SELECT            *
FROM     ( SELECT *,
                 CASE
                         WHEN name = 'qqq'
                         THEN 1
                         WHEN name LIKE 'qqq%'
                         THEN 2
                         WHEN name LIKE '%qqq%'
                         THEN 3
                         ELSE 0
                 END AS weight
         FROM    t
         )
         q
WHERE    q.weight > 0
ORDER BY q.weight,
         q.name
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜