我有一个大约有800万行的表。行包含一个ID、一个日期和一个事件代码。我希望选择事件代码等于1的所有ID和日期,并且在过去的某个时候有一个事件代码等于2。
例如,我的表如下所示:
ID Date Code
----------------------
1 4/16/2016 6
1 4/10/2016 1
1 3/1/2016 13
1 1/26/2016 2
2 5/2/2016 8
2 3/14/2016 1
2 1/13/2016 14我希望ID =1和Date = 4/10/2016返回,但是我不希望ID=2返回任何内容,因为ID=2从来没有一个等于2的事件代码。
我应该如何编写我的SELECT语句来获得这些结果?
发布于 2016-05-09 23:43:18
您可以使用exists。
select *
from t
where code = 1 and
exists (select 1 from t t1 where t.id = t1.id and t.dt > t1.dt and t1.code=2)发布于 2016-05-09 23:47:12
select id
, max(date)
from table to
where to.code = 1
and exists (select 1 from table ti where ti.id = to.id AND ti.code = 2)
group by id发布于 2016-05-09 23:54:13
@vkp有最好的答案。但是,这里有一种使用窗口函数的方法:
select t.id, t.code, t.dt
from (select t.*, min(case when code = 2 then dt end) over (partition by id) as dt_2
from t
where code in (1, 2)
) t
where t.code = 1 and dt_2 < dt;https://stackoverflow.com/questions/37127099
复制相似问题