如何检查选择一个值的数据?

时间:2015-05-11 11:37:29

标签: sql sql-server

不能为我的选择制作写脚本。

我有这样的表有一些服务:

+----------+-------------+------------+
| Serv_cod |  Start_Date |  End_Date  |
+----------+-------------+------------+
|       1  | 01/03/2015  | 01/03/2999 |
|       2  | 20/03/2015  | 20/03/2999 |
|       2  | 01/01/2012  | 18/03/2015 |
|       3  | 13/03/2015  | 13/03/2999 |
|       3  | 03/05/2011  | 12/02/2015 |
|       4  | 14/03/2009  | 27/03/2015 |
|       4  | 28/03/2015  | 28/03/2999 |
+----------+-------------+------------+

我只需要选择在服务结束后不超过5天内开始的服务。我想得到这样的结果:

+----------+-------------+------------+
| Serv_cod |  Start_Date |  End_Date  |
+----------+-------------+------------+
|       2  | 20/03/2015  | 20/03/2999 |
|       2  | 01/01/2012  | 18/03/2015 |
|       4  | 14/03/2009  | 27/03/2015 |
|       4  | 28/03/2015  | 28/03/2999 |
+----------+-------------+------------+

我试图用这样的脚本解决它:

select * from serv 
where serv_cod in ( 
select serv_cod from serv a
inner join serv b
on a.serv_cod=b.serv_code
where a.start_date between b.end_date - 5 and b.end_date  )

但我没有得到我想要的结果。 有人可以帮忙吗? 提前谢谢!

1 个答案:

答案 0 :(得分:0)

假设间隔不重叠,在SQL Server 2012+中,您可以使用lag()

select s.*
from (select s.*,
             lag(end_date) over (partition by serv_code order by start_date) as prev_end_date
      from serv s
     ) s
where start_date <= dateadd(day, 5, prev_end_date) and
      start_date >= prev_end_date

否则,你总是可以使用exists

select s.*
from serv s
where exists (select 1
              from serv s2
              where s.start_date <= dateadd(day, 5, s2.end_date) and
                    s.start_date >= s2.end_date
             );