Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

to find even odd and plain series in postgresql

this might be naive but I want to know is there any way possible to find rows which have even entries and which have odd. I have data in this format

"41,43,45,49,35,39,47,37"
"12,14,18,16,20,24,22,10"
"1,2,3,4,5,6"
"1,7,521,65,32"

what I have tried is to split these values with an Id column and then reading them with Even and Odd functions but it is too time taking. is there a query or a function through I can find out that which of the rows are even, odd sequence and arbitrary?

thanks in advance.

like image 819
dspl Avatar asked Jan 28 '15 08:01

dspl


1 Answers

Assuming your table has some way of (uniquely) identifying each of those lists, this should work:

create table data (id integer, list text);

insert into data 
values
(1, '41,43,45,49,35,39,47,37'),
(2, '12,14,18,16,20,24,22,10'),
(3, '1,2,3,4,5,6'),
(4, '1,7,521,65,32');


with normalized as (
  select id, unnest(string_to_array(list,',')::int[]) as val
  from data
)
select id, 
       bool_and((val % 2) = 0) as all_even,
       bool_and((val % 2) <> 0) as all_odd
from normalized
group by id;

Not sure if that is fast enough for your needs

like image 167
a_horse_with_no_name Avatar answered Oct 07 '22 21:10

a_horse_with_no_name