假设我在'SELECT'请求的'WHERE'子句中有10个条件。
我只需要显示满足至少5个条件的结果,并按满足条件的数量排序:10,9,8…
我怎样才能做到这一点呢?
这可能会根据您使用的DBMS略有不同,但对于MS-SQL, WHERE子句可以分割为单独的CASE语句,然后对其进行求和和排序:
SELECT
*,
CASE WHEN (CONDITION 1) THEN 1 ELSE 0 END
+ CASE WHEN (CONDITION 2) THEN 1 ELSE 0 END
(...)
+ CASE WHEN (CONDITION 10) THEN 1 ELSE 0 END AS MatchCount
FROM MyTable
ORDER BY MatchCount DESC
你可以把它包装成一个子查询来得到至少匹配5的结果:
SELECT *
FROM (
SELECT
*,
CASE WHEN (CONDITION 1) THEN 1 ELSE 0 END
+ CASE WHEN (CONDITION 2) THEN 1 ELSE 0 END
(...)
+ CASE WHEN (CONDITION 10) THEN 1 ELSE 0 END AS MatchCount
FROM MyTable) T
WHERE T.MatchCount >= 5
ORDER BY MatchCount DESC