Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- id: 1,
- name: "my group",
- filters: [
- {field: "sessions", type: "greater_than", value: 5},
- {field: "email", type: "contains", value: "@example.com}
- ]
- id: 1, email: "example@gmail.com", sessions: 5, more_meta_data..
- id: 1, matching_groups: ["my group"], email: "example@gmail.com", sessions: 5 more_meta_data..
- create table groups (id int, name text, filters text[]);
- insert into groups values
- (1, 'group1', array['sessions > 0', 'email like ''example%''']),
- (2, 'group2', array['sessions > 5', 'email like ''example%''']),
- (3, 'group3', array['sessions = 5', 'email like ''%gmail.com''']);
- create table visitors (id int, email text, sessions int);
- insert into visitors values
- (1, 'example@gmail.com', 5),
- (2, 'example@abc.com', 10),
- (3, 'me@gmail.com', 5),
- (4, 'xxx@yyy.com', 5);
- create or replace function the_filter(filters text[], id int)
- returns boolean language plpgsql as $$
- declare
- r boolean;
- begin
- execute format(
- 'select %s from visitors where id = %s',
- array_to_string(filters, ' and '),
- id)
- into r;
- return r;
- end $$;
- select v.*, array_agg(g.name) groups
- from visitors v
- left join groups g on the_filter(g.filters, v.id)
- group by 1, 2, 3;
- id | email | sessions | groups
- ----+-------------------+----------+-----------------
- 1 | example@gmail.com | 5 | {group1,group3}
- 2 | example@abc.com | 10 | {group1,group2}
- 3 | me@gmail.com | 5 | {group3}
- 4 | xxx@yyy.com | 5 | {NULL}
- (4 rows)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement