Search code examples
sqlfilterdata-manipulationhaving

SQL: subset data: select id when time_id for id satisfy a condition from another column


I have a data (dt) in SQL like the following:

 ID     time_id  act  rd
 11        1      1    1
 11        2      4    1
 11        3      7    0
 12        1      8    1
 12        2      2    0
 12        3      4    1
 12        4      3    1
 12        5      4    1
 13        1      4    1
 13        2      1    0
 15        1      3    1
 16        1      8    0
 16        2      8    0
 16        3      8    0
 16        4      8    0
 16        5      8    0

and I want to take the subset of this data such that only ids (and their corresponding time_id, act, rd) that has time_id == 5 is retained. The desired output is the following

 ID     time_id  act  rd     
 12        1      8    1
 12        2      2    0
 12        3      4    1
 12        4      3    1
 12        5      4    1
 16        1      8    0
 16        2      8    0
 16        3      8    0
 16        4      8    0
 16        5      8    0

I know I should use having clause somehow but have not been successful so far (returns me empty outputs). below is my attempt:

SELECT * FROM dt GROUP BY ID Having min(time_id) == 5;


Solution

  • This query:

    select id from tablename where time_id = 5
    

    returns all the ids that you want in the results.
    Use it with the operator IN:

    select *
    from tablename
    where id in (select id from tablename where time_id = 5)