【问题标题】:SQL: subset data: select id when time_id for id satisfy a condition from another columnSQL:子集数据:当id的time_id满足另一列的条件时选择id
【发布时间】:2020-11-08 23:59:32
【问题描述】:

我在 SQL 中有一个数据 (dt),如下所示:

 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

我想获取此数据的子集,以便仅保留具有 time_id == 5 的 ids(及其相应的 time_id、act、rd)。所需的输出如下

 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

我知道我应该以某种方式使用having子句,但到目前为止还没有成功(返回空输出)。以下是我的尝试:

从 dt 中选择 * 按 ID 分组 有 min(time_id) == 5;

【问题讨论】:

    标签: sql filter data-manipulation having


    【解决方案1】:

    这个查询:

    select id from tablename where time_id = 5
    

    在结果中返回您想要的所有ids。
    与运算符IN一起使用:

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

    【讨论】:

      【解决方案2】:

      您可以使用带有exists 的相关子查询:

      select t.*
      from t
      where exists (select 1 from t t2 where t2.id = t.id and t2.time_id = 5);
      

      【讨论】:

        【解决方案3】:
        WITH temp AS
        (
        SELECT id FROM tab WHERE time_id = 5
        )
        SELECT * FROM tab t join temp tp on(t.id=tp.id);
        

        【讨论】:

          【解决方案4】:

          检查这个查询

           select * from table t1 join (select distinct ID from table t where time_id = 5) t2 on  t1.id =t2.id;
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2011-10-16
            • 1970-01-01
            • 1970-01-01
            • 2021-08-25
            相关资源
            最近更新 更多