0

I have an SQL query which look like this

SELECT t.test1 AS test01
FROM my_test_table t
WHERE t.test01 LIKE any('{data_nr0%,data_nr1%,data_a%}')

It works and everything is fine, but I don't know how to enhance it that in the output it would include extra pieces of data that are in ANY().

I need an output to be

test01 parameter_
data_nr0123 data_nr0
data_nr0122 data_nr0
data_nr0124 data_nr0
data_nr1123 data_nr1
data_nr1122 data_nr1
data_nr1124 data_nr1
data_a123 data_a

where parameter_ column has values that are inside ANY() operator.

UPDATE NO. 1

Tried

SELECT SUBSTRING(t.test1, 1, 8), t.test1 AS test01
FROM my_test_table t
WHERE t.test01 LIKE any('{data_nr0%,data_nr1%}')

but this works only if values in ANY operator are of the same length. How to make it work with variable length values?

1 Answer 1

1

Find a relevant match with CASE

SELECT case when t.test01 LIKE 'data_nr0%' then 'data_nr0'
            when t.test01 LIKE 'data_nr1%' then 'data_nr1' end param
, t.test1 AS test01
FROM my_test_table t
WHERE t.test01 LIKE any('{data_nr0%,data_nr1%}')

Alternatively you can have a parameters table / cte, then

-- sample data
with my_test_table(test01) as(
    select 'data_nr01' union all
    select 'data_nr13' 
),
params(val) as (
    select 'data_nr0' union all
    select 'data_nr1' 
)
SELECT t.test01, min(p.val)
FROM my_test_table t
JOIN params p on t.test01 like p.val||'%'
GROUP BY t.test01
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your response, what if there are many values inside ANY() (let's say 100 values), should I write them all in case... when... Or is there a better approach?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.