简体   繁体   中英

SQL - matching 3 from 5 criterias

Is it possible with sql (postgres) to make a query which searches for entries which match any 3 criterias of 5 possible? I am not getting anywhere at the moment and i am stuck. Plz, help out.

This is a verbose, yet straight-forward solution to this problem:

SELECT * FROM t
WHERE (CASE t.val WHEN :criteria1 THEN 1 ELSE 0 END +
       CASE t.val WHEN :criteria2 THEN 1 ELSE 0 END +
       CASE t.val WHEN :criteria3 THEN 1 ELSE 0 END +
       CASE t.val WHEN :criteria4 THEN 1 ELSE 0 END +
       CASE t.val WHEN :criteria5 THEN 1 ELSE 0 END) >= 3

You could also do tricks with semi-joining an unnested array:

SELECT * FROM t
WHERE (
  SELECT COUNT(*) 
  FROM UNNEST(ARRAY[:c1, :c2, :c3, :c4, :c5]) u(val)
  WHERE u.val = t.val
) >= 3

Or by semi-joining a VALUES(...) expression

SELECT * FROM t
WHERE (
  SELECT COUNT(*) 
  FROM (VALUES (1), (1), (2), (2), (2)) u(val)
  WHERE u.val = t.val
) >= 3

Here's a working example, which I've put on SQL Fiddle :

WITH t(val) AS (
  VALUES (1), (2), (4), (6)
)
SELECT * FROM t
WHERE (
  SELECT COUNT(*) 
  FROM (VALUES (1), (1), (2), (2), (2)) u(val)
  WHERE u.val = t.val
) >= 3

The above will return 2, as it is the only record that matches at least three criteria among (1, 1, 2, 2, 2)

SELECT * FROM table 
WHERE IF(crit1, 1,0)
+ IF(crit2, 1,0)
+ IF(crit3, 1,0)
+ IF(crit4, 1,0)
+ IF(crit5, 1,0) >= 3

[Edit] As per below comment this is not valid postgres. This is how it would be done in MySQL, I just assumed it's standard... The CASE statement is more relevant to the original question.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM