sql:子集数据:当id的time\u id满足另一列的条件时选择id

w41d8nur  于 2021-07-24  发布在  Java
关注(0)|答案(4)|浏览(317)

我在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

我想取这个数据的子集,这样只有id(以及它们对应的time,act,rd)保留time,id==5。所需输出如下

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 group by id中选择*min(time_id)==5;

wlp8pajw

wlp8pajw1#

WITH temp AS
(
SELECT id FROM tab WHERE time_id = 5
)
SELECT * FROM tab t join temp tp on(t.id=tp.id);
x4shl7ld

x4shl7ld2#

检查此查询

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

gfttwv5a3#

此查询:

select id from tablename where time_id = 5

返回所有 id 这是你想要的结果。
与操作员一起使用 IN :

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

x759pob24#

可以将相关子查询与 exists :

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

相关问题