按最大条件匹配排序 [英] Order by Maximum condition match
本文介绍了按最大条件匹配排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
请帮助我创建一个包含10个"where"子句的选择查询,其顺序应如下所示: 结果应按大多数关键字(条件)匹配到不匹配的顺序显示.
Please help me to create a select query which contains 10 'where' clause and the order should be like that: the results should be displayed in order of most keywords(where conditions) matched down to least matched.
注意:所有10个条件都带有或".
NOTE: all 10 condition are with "OR".
请帮助我创建此查询. 我正在使用ms-sql server 2005
Please help me to create this query. i am using ms-sql server 2005
赞:
Select *
from employee
where empid in (1,2,4,332,434)
or empname like 'raj%'
or city = 'jodhpur'
or salary >5000
在上面的查询中,所有与最大条件匹配的记录都应位于顶部,而较少匹配条件的记录应位于底部.
In above query all those record which matches maximum conditions should be on top and less matching condition record should be at bottom.
推荐答案
SELECT *
FROM (SELECT (CASE WHEN cond1 THEN 1 ELSE 0 END +
CASE WHEN cond2 THEN 1 ELSE 0 END +
CASE WHEN cond2 THEN 1 ELSE 0 END +
...
CASE WHEN cond10 THEN 1 ELSE 0 END
) AS numMatches,
other_columns...
FROM mytable
) xxx
WHERE numMatches > 0
ORDER BY numMatches DESC
这篇关于按最大条件匹配排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文