根据相同的条件语句SQL选择两列

时间:2014-10-13 15:04:47

标签: sql database postgresql amazon-redshift

我有一个类似于此类的

的select语句
SELECT
    CASE WHEN <SOME-CONDN_1> THEN 'value1' ELSE '' ||
    CASE WHEN <SOME-CONDN_2> THEN 'value2' ELSE '' ||
    CASE WHEN <SOME-CONDN_3> THEN 'value3' ELSE '' AS value_column,
    CASE WHEN <SOME-CONDN_1> THEN 'name1' ELSE '' ||
    CASE WHEN <SOME-CONDN_2> THEN 'name2' ELSE '' ||
    CASE WHEN <SOME-CONDN_3> THEN 'name3' ELSE '' AS name_column
FROM data_table
--<REST OF THE QUERY>

条件语句类似于data_table.data_column ILIKE value1等等。 由于我做了两次相同的条件语句(并且它涉及使用ILIKE进行一些字符串匹配),我想知道我是否可以将它们联系起来并使其更有效率。

使用SQL语句是否也可以这样做?

2 个答案:

答案 0 :(得分:1)

选项1:不太确定CASE的这种变体是否适用于PostgreSQL ......

select case cond_num when 
    1 then 'value1'
    when 2 then 'value2',
    when 3 then 'value3' else null end as value_column,
case cond_num when 
    1 then 'name1'
    when 2 then 'name2',
    when 3 then 'name3' else null end as name_column
from (
select data_table.*,
    case when <some_condition_1> then 1 
    when <some_condition_2> then 2
    when <some_condition_3> then 3 else 0 end as cond_num
from data_table
) screened_table
;

选项2:

select case when 
    cond1 = 1 then 'value1'
    when cond2 = 1 then 'value2',
    when cond3 = 1 then 'value3' else null end as value_column,
case when 
    cond1 = 1 then 'name1'
    when cond2 = 1 then 'name2',
    when cond3 = 1 then 'name3' else null end as name_column
from (
select data_table.*,
    case when <some_condition_1> then 1 else 0 as cond1,
    case when <some_condition_2> then 1 else 0 as cond2,
    case when <some_condition_3> then 1 else 0 as cond3
from data_table
) screened_table
;

选项3 - 注意条件不是独占的可以返回多行。不会从data_table返回没有条件的行。

select rslt.name, rslt.value
from data_table, (
    select 1 as cond, 'value1' as value, 'name1' as name
    union all
    select 2 as cond, 'value2' as value, 'name2' as name
    union all
    select 3 as cond, 'value3' as value, 'name3' as name
) rslt
WHERE (<some_condition_1> and rslt.cond = 1) OR
    (<some_condition_2> and rslt.cond = 2) OR
    (<some_condition_3> and rslt.cond = 3)

答案 1 :(得分:0)

假设结果都是字符串,您可以使用数组来简化操作。

SELECT a[1],a[2], ...
FROM (SELECT CASE 
        WHEN <SOME-CONDN_1> THEN ARRAY['value1','name1'] 
        WHEN <SOME-CONDN_2> THEN ARRAY['value2','name2'] 
        WHEN <SOME-CONDN_3> THEN ARRAY['value3','name3'] 
        ELSE '' AS a
    FROM ...
);

如果结果值不是所有相同的类型,你可以使用ROW()构造函数执行相同的操作,但是您需要定义一个类型以便单独获取值&#34;退出行& #34;