在SQL中重叠日期

时间:2017-09-06 06:35:45

标签: sql-server

我想要一个查询来识别具有不同Vehicle Registration Numbers的多个政策的Insurance Company ID,并且日期重叠。 Check this image for the datas

 SELECT Vehicle_N0.*
   FROM excel as Vehicle_N0
  WHERE Vehicle_N0 IN (SELECT Vehicle_N0  
                         FROM excel 
                        GROUP BY Vehicle_N0    
                       HAVING COUNT(DISTINCT Insurance_id) > 1) 
  ORDER BY vehicle_n0

使用此查询,Vehicle Registration Numbers的政策不止一个Insurance Company ID,但如何获取重叠日期。

我试过了这个查询

SELECT * 
  FROM excel 
 WHERE begin_date <= end_date 
    OR begin_date >= end_date;

但我没有得到重叠的日期。

1 个答案:

答案 0 :(得分:2)

使用exists()查看Vehicle_N0是否有重叠的条目与Insurance_Id不同:

select v.*
from excel as v
where exists ( -- only return rows where this query would return row(s)
  select 1
  from excel as i 
  where i.Vehicle_N0 = v.Vehicle_N0      -- Vehicle_N0 is the same
    and i.Insurance_Id <> v.Insurance_Id -- Insurance_Id is not the same
    and i.end_date > v.begin_date        -- date range overlaps
    and v.end_date > i.begin_date        -- date range overlaps
  )
order by v.Vehicle_N0