简体   繁体   English

查询以查找一组列中至少一个值的出现

[英]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. 在下表中,如何过滤掉任何一列中至少包含1和至少2的记录。 I also only want records for columns with the string 2nd row in the Name column. 我还只希望在Name列中记录字符串2nd row的列。

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 ... . 您可以将IN用作"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: 您可以使用Postgres的数组:

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. Coalesce()是必需的,因为您不能将空值放入数组中。

Online example: https://rextester.com/CLXWK64603 在线示例: https//rextester.com/CLXWK64603

If you want you can create an index on the array expression to speed things up. 如果需要,可以在数组表达式上创建索引以加快处理速度。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 基于集合的查询,以查找表中包含至少一个空值的所有列 - Set-based query to find all columns in table that contain at least one null value 查询以找到资产表中至少具有一个值的地区 - Query to find districts with at least one value in assets table SQL Server查询以查找按一列分组但在其他至少一列中不同的值 - SQL server query to find values grouped by one column but different in at least one of other columns PostgreSQL查询列上具有最少空值的行 - PostgreSQL query rows with least null value on columns 列出至少有一行针对特定查询的具有非空值的表的列 - List columns of table on which there is at least one row with a non null value for a specific query SQL查询以查找至少一天的行数大于或等于阈值的用户的最小值和最大值 - SQL query to find min and & max value for a user who has at least one day with a row count of > threshold 在关系表中显示至少出现一次的行? - Show rows with at least one occurrence in a relation table? SQL 当至少有一个值等于 value 然后设置为 value 的情况 - SQL Case when at least one value equals value then set to value 如何过滤出至少出现一次值的组? - How do I filter out a group where there is at least one occurrence of a value? SQL:从一行的一列中获取至少第三大值 - SQL: Get at least the Third Largest Value from a set of columns of a row
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM