简体   繁体   中英

PSQL filter each group of rows

Recently I've faced with pretty rare filtering case in PSQL. My question is: How to filter redundant elements in each group of the grouped table?

For example: we have a nexp table:

id  |  group_idx  |  filter_idx
 1          1             x
 2          3             z
 3          3             x
 4          2             x
 5          1             x
 6          3             x
 7          2             x
 8          1             z
 9          2             z

Firstly, to group rows:

SELECT group_idx FROM table
GROUP BY group_idx;

But how I can filter redundant fields (filter_idx = z) from each group after grouping?

PS I can't just write like that because I need to find groups firstly.

SELECT group_idx FROM table
where filter_idx <> z;

Thanks.

Assuming that you want to see all groups at all times, even when you filter out all records of some group:

drop table if exists test cascade;
create table test (id integer, group_idx integer, filter_idx character);
insert into test
(id,group_idx,filter_idx)
values
(1,1,'x'),
(2,3,'z'),
(3,3,'x'),
(4,2,'x'),
(5,1,'x'),
(6,3,'x'),
(7,2,'x'),
(8,1,'z'),
(9,2,'z'),
(0,4,'y');--added an example of a group that would be discarded using WHERE.

Get groups in one query, filter your rows in another, then left join the two.

select  groups.group_idx,
        string_agg(filtered_rows.filter_idx,',')
from 
    (select distinct group_idx from test) groups
    left join 
    (select group_idx,filter_idx from test where filter_idx<>'y') filtered_rows
        using (group_idx)
group by 1;
-- group_idx | string_agg
-------------+------------
--         3 | z,x,x
--         4 |
--         2 | x,x,z
--         1 | x,x,z
--(4 rows)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM