简体   繁体   中英

SQL: Need to select rows where at least 3 columns are not equal to specific value

I need to select rows where at least three columns are not equal to "Unknown"

Example dataset:

id     condition_A      condition_B      condition_C     condition_D     Condition_E    
1      Unknown          Positive         Negative        Negative        Unknown
2      Unknown          Unknown          Negative        Negative        Unknown
3      Positive         Positive         Negative        Negative        Unknown

In this case I would want the query to return rows 1 and 3.

I think this will do it:

select * from tablename
where 3 <=
  (condition_A <> 'Unknown')::int + 
  (condition_B <> 'Unknown')::int + 
  (condition_C <> 'Unknown')::int + 
  (condition_D <> 'Unknown')::int + 
  (condition_E <> 'Unknown')::int

See the demo .
Results:

| id  | condition_a | condition_b | condition_c | condition_d | condition_e |
| --- | ----------- | ----------- | ----------- | ----------- | ----------- |
| 1   | Unknown     | Positive    | Negative    | Negative    | Unknown     |
| 3   | Positive    | Positive    | Negative    | Negative    | Unknown     |

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