Skip to content
Advertisement

Select based on group membership

Suppose I have two tables t and o. I want to select all the rows of t in which t.feature = o.feature (ergo first two rows).

In addition, I also want to select all the rows whose t.grouping = t.grouping of the previously selected rows. In this case t.grouping 1, 2 ergo rows ('E', 1), ('F', 2) and ('G', 1). What is the most elegant way of achieving this?

CREATE TABLE t
(   feature      VARCHAR,
    grouping            BIGINT
);

INSERT INTO t (feature, grouping)
VALUES ('A', 1), 
        ('B', 2),
        ('C', 5), 
        ('D', 4),
        ('E', 1), 
        ('F', 2),
        ('G', 1);
        
        
CREATE TABLE o
(   feature VARCHAR
);

INSERT INTO o (feature)
VALUES ('A'),
       ('B');

Advertisement

Answer

If I understood correctly try this…

with cte as 
(select grouping from t inner join o on t.feature=o.feature)
select t.* 
from t 
inner join cte on t.grouping=cte.grouping

or

select 
* 
from t 
where grouping in 
(select grouping from t inner join o on t.feature=o.feature )

DEMO

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement