select 第一个匹配列
select first matching column
我有多个列的数据
col_a | col_b | col_c
-----------------------------------------------
good car | medium sandwitch | good computer
bad computer | good wall | bad wall
我想select这三列中第一个以“good
”开头的值
result
---------
good car
good wall
您可以使用一个简单的 case
表达式来做到这一点:
select case
when col_a like 'good%' then col_a
when col_b like 'good%' then col_b
when col_c like 'good%' then col_c
end result
from table
这将按顺序计算,因此请按照您希望检查的任何顺序对 case 语句中的列进行排序。
--编辑--
要删除没有结果的行,我们有几种选择:
将其移动到带有 where
子句的子查询(或 CTE)中
select *
from
(
select case
when col_a like 'good%' then col_a
when col_b like 'good%' then col_b
when col_c like 'good%' then col_c
end result
from table
) a
where a.result is not null
在你的 where
子句中检查所有这些
select case
when col_a like 'good%' then col_a
when col_b like 'good%' then col_b
when col_c like 'good%' then col_c
end result
from table
where col_a like 'good%'
or col_b like 'good%'
or col_c like 'good%'
我有多个列的数据
col_a | col_b | col_c
-----------------------------------------------
good car | medium sandwitch | good computer
bad computer | good wall | bad wall
我想select这三列中第一个以“good
”开头的值
result
---------
good car
good wall
您可以使用一个简单的 case
表达式来做到这一点:
select case
when col_a like 'good%' then col_a
when col_b like 'good%' then col_b
when col_c like 'good%' then col_c
end result
from table
这将按顺序计算,因此请按照您希望检查的任何顺序对 case 语句中的列进行排序。
--编辑--
要删除没有结果的行,我们有几种选择:
将其移动到带有 where
子句的子查询(或 CTE)中
select *
from
(
select case
when col_a like 'good%' then col_a
when col_b like 'good%' then col_b
when col_c like 'good%' then col_c
end result
from table
) a
where a.result is not null
在你的 where
子句中检查所有这些
select case
when col_a like 'good%' then col_a
when col_b like 'good%' then col_b
when col_c like 'good%' then col_c
end result
from table
where col_a like 'good%'
or col_b like 'good%'
or col_c like 'good%'