2016-08-04 97 views
1

比较我有一个名为feature表作为SQL查询字符串转换为数组,然后用一些条件

sample_value      operator_seq   actual_value 
ID:Desktop|Height:627|Width:768 =,>,>   ID:Desktop|Height:600|Width:1024 
ID:Desktop|Height:627|Width:768 =,>,>   ID:Desktop|Height:600|Width:600 

sample_valueactual_value如果我们分裂基于|分隔符为三个子字符串。如果我们根据,定界符分割运算符,我们也有三个运算符。

现在我想的sample_value第一子串比较的actual_value第一子串用第一运营商的sample_valueactual_value第二子串第二子字符串中使用第二运营商等等...

基本上该查询将看起来像

if (
    (sample_value.fisrt_substr operator_seq.first_operator actual_value.first_substr) and 
    (sample_value.second_substr operator_seq.second_operator actual_value.second_substr) and 
    (sample_value.third_substr operator_seq.third_operator actual_value.third_substr) 
) Then 1 else 0 

所以用于第一行的输出将是0(因为条件(宽度:768>宽度:1024)为假)和第二行输出将为1(所有三个条件满足)。

输出表如下所示:

sample_value     operator_seq   actual_value   result 
ID:Desktop|Height:627|Width:768 =,>,>  ID:Desktop|Height:600|Width:1024 0 
ID:Desktop|Height:627|Width:768 =,>,>  ID:Desktop|Height:600|Width:600 1 

如何编写该查询。

+0

[评估条件](http://pastebin.com/896FJfKA)老实说它是 “玩票”解决方案,如果你仍然想使用纯SQL来完成。它适用于您的示例数据,但看起来很丑并且有一些限制(例如关于参数的类型)。我的建议是创建存储的函数来计算条件。 – Abelisto

+0

感谢您的回复。但是我对存储过程了解不多。这很紧急。所以请尽可能请你提出相同的查询。再次感谢。 –

+0

正如许多次所说:“它不是一个代码写作网站”。如果你不太了解存储过程,那么,至少目前这个任务可能不适合你。 – Abelisto

回答

0

创建一个函数:

create or replace function evalBoolean(arg1 text,op text,arg2 text) returns boolean 
as 
$body$ 
declare 
    result boolean; 
begin 
    execute 'select $$'||arg1||'$$'||op||'$$'||arg2||'$$' into result; 
    return result; 
end;$body$ 
language plpgsql 

而且使用这样的:

select * 
    ,evalBoolean(sv[1],op[1],act[1]) and evalBoolean(sv[2],op[2],act[2]) and evalBoolean(sv[3],op[3],act[3]) 
    from (
    select string_to_array(sample_value,'|') sv 
      ,string_to_array(operator_seq,',') op 
      ,string_to_array(actual_value,'|') act 
     from your_table 
) a 
+0

非常感谢。它正在工作。需要稍微改变以适合我的数据。你救了我。再次感谢。 –

相关问题