用于检索两个日期范围的结果集的SQL

时间:2017-01-09 19:30:59

标签: sql

我需要一个SQL语句,它将返回一个结果集,其中包含一个时间帧之间状态代码为“DE”的人员ID,以及另一个时间帧之间的状态代码“PE”。 示例表

id | name 
--- ------
1    Joe  
2    Jane 

status | start_date | end_date  | person_id
------- ------------ ----------- -----------
   DE    2016-12-01  2016-12-28   1
   PE    2017-02-01  2017-02-28   1
   DE    2016-12-01  2016-12-28   2

如果'DE'时间范围介于2016-12-01和2016-12-28之间且'PE'时间范围介于2017-02-01和2017-02-28之间,我希望Joe能够在查询集。

3 个答案:

答案 0 :(得分:1)

对于这样的问题,最好的办法是将它们分解为单独的SQL,因此请在此表中进行两次。一次为styleUrls,另一次为DE

PE

现在你必须得到可以相互测试的结果集:

SELECT name FROM table WHERE status = 'DE' and start_date = '2016-12-01' AND end_date = '2016-12-28';

SELECT name FROM table WHERE status = 'PE' and start_date = '2017-02-01' AND end_date = '2017-02-28';

由于您实际上没有从第二个派生表中进行选择,因此您可以使用相同的逻辑来使用相关的子查询:

SELECT name 
FROM
    (SELECT name FROM table WHERE status = 'DE' and start_date = '2016-12-01' AND end_date = '2016-12-28') t1
    INNER JOIN (SELECT name FROM table WHERE status = 'DE' and start_date = '2016-12-01' AND end_date = '2016-12-28') t2 ON t1.name = t2.name;

哪个可能表现更好。

答案 1 :(得分:0)

我不明白你需要什么。

但是,

SELECT * FROM table1 where (select count(*) from table2 where table1.id = table2.person_id and (([status] = 'DE' and start_data between '2016-12-01' and '2016-12-28') or ([status] = 'PE' and start_data between '2017-02-01' and '2017-02-28')) > 0

答案 2 :(得分:0)

我不知道你正在使用哪个sql,但这个查询应该可以正常使用PostgreSQL

select Res.name from   (
                select * from table1 inner join table2 on Table1.id = Table2.person_id
                where (status = 'DE' and start_date >= '2016-12-01' and end_date <= '2016-12-28') 
                or
                (status = 'PE' and start_date >= '2017-02-01' and end_date <= '2017-02-28')
                    ) as Res
    group by Res.name having count(*) > 1

或者您也可以使用此声明

select table1.name from  table1 
inner join table2 t1 on table1.id = t1.person_id
where status = 'DE' and start_date >= '2016-12-01' and end_date <= '2016-12-28' 
and 
exists ( select 1 from table2 t2 where t2.person_id = t1.person_id and 
status = 'PE' and start_date >= '2017-02-01' and end_date <= '2017-02-28' )