简体   繁体   中英

Query to find occurrence of at least one value in a set of columns

In the below table, how do I filter out records with at least one 1 and at least one 2 in any of the columns. I also only want records for columns with the string 2nd row in the Name column.

Col1 Col2 Col3 Col4 Name
1    1    1    1    1st row
1    2    1    2    2nd row
2    1    1    1    3rd row
1    2              2nd row

I want the output to be -

Col1 Col2 Col3 Col4 Name 
1    2    1    2    2nd row
1    2              2nd row

You can use IN as a shortcut for "col1" = 1 OR ... .

SELECT *
       FROM "elbat"
       WHERE 1 IN ("col1",
                   ...,
                   "col4")
             AND 2 IN ("col1",
                       ...,
                       "col4")
             AND "name" = '2nd row';

You can use Postgres' arrays for that:

select *
from the_table
where array[1,2] <@ array[coalesce(col1, -1), coalesce(col2, -1), coalesce(col3, -1), coalesce(col4, -1)] 
  and name = '2nd row';

The <@ operator checks, if all elements of the left hand array are included in the right hand array. The coalesce() is necessary because you can't put null values into an array.

Online example: https://rextester.com/CLXWK64603

If you want you can create an index on the array expression to speed things up.

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