我在SQL Server 2008中有这个表“保险”
insuranceId StartDate EndDate CarID
1 1-jan-2010 1-Jan-2011 1
2 2-Jan-2011 2-Jan-2012 1
3 1-Jan-2012 1-Jan-2012 2
我需要写查询返回:
汽车连续两次保险
这个数据库对于保险公司我需要获得连续两次保险的汽车
在另一个词中获取汽车的记录中的Enddate =(startdate + 1)在汽车的另一个记录中
对于这个表我需要得到carId = 1,因为
EndDate in Firstrecord = 1-Jan-2011 and the StartDate in second record = 2-Jan-2011
答案 0 :(得分:2)
据我了解,这给出了你想要的东西:
SELECT io.CarID
FROM insurance AS io
WHERE DATEADD(DAY, 1, io.EndDate) IN
(SELECT ii.StartDate
FROM insurance AS ii
WHERE ii.CarID = io.CarID);
答案 1 :(得分:-2)
SELECT TOP 2 * FROM insurance WHERE insuranceId > 1 ORDER BY insuranceId
其中1是您需要的第一辆汽车的ID。