需要编写查询以选择从特定日期开始处于活动状态的记录,当前状态可以是活动的,也可以是不活动的,它们属于类别学生。
表==>
id category date-from date-to status
1 student 01/01/2015 12/01/2020 active
1 student 12/01/2020 01/01/9999 active
2 employee 01/01/2018 01/01/9999 active
3 student 10/05/2015 01/01/2016 active
3 student 01/01/2016 01/01/9999 inactive
希望获得截至2015年1月6日处于活动状态的学生,但当前状态可以是活动的或不活动的 需要获取他们的当前状态,id,当前状态
答案 0 :(得分:0)
如果您希望在给定日期活跃的学生,则可以过滤表格,如下所示:
select t.*
from mytable t
where
date '2020-06-01' >= date_from
and date '2020-06-01' < date_to
and status = true
and category = 'student'
您没有告诉您正在使用哪个数据库-这使用标准语法声明日期文字。
答案 1 :(得分:0)
select t.*
from t
where t.type = 'student' and
t.date_to > current_date and
exists (select 1
from t t2
where t2.id = t.id and
t2.status = 'active' and
date '2015-06-01' >= t2.date_from and
date '2015-06-01' < t2.date_to
);
注意:这使用标准的SQL语法。日期函数和常量众所周知是依赖数据库的。但是这个想法应该适用于任何数据库。