2017-09-06 60 views
2

我想要一個查詢來識別具有多個1策略的Vehicle Registration Numbers,其中Insurance Company ID的日期重疊。 Check this image for the datasSQL中的重疊日期

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 

使用此查詢,我得到具有不同Insurance Company ID超過1個政策,如何讓重疊的日期Vehicle Registration Numbers

我嘗試這個查詢

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

,但我沒有得到重疊的日期。

+2

請張貼預期結果,實際結果爲文本,而不是圖像 – TheGameiswar

+0

預期的結果是我想要得到的重疊日期從我的桌子上。我試圖做到這一點,但我失敗了 –

+0

看看這個鏈接,以瞭解更多關於如何改善問題:https://spaghettidba.com/2015/04/24/how-to-post-at-sql-question- on-a-public-forum/ – TheGameiswar

回答

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 
+0

你能exaplain我怎麼這個查詢工作? ? –

+0

我得到了正確的結果,但是,我不明白它是如何工作的...... –

+0

@JeroldJoel我已經更新了我的答案並提供了一些評論,讓我知道是否有幫助。有沒有你不明白的特定部分? – SqlZim