2016-03-10 25 views
1

我正在嘗試創建一個查詢來評估特定車輛的所有者是否在某個時間點。車輛的目擊量包含在vehicle_sightings表格中。這個查詢有一點棘手,那就是vehicle_vrn和vehicle_ownership表是歷史性的。因此,我需要做的是獲得車輛的VRN和所有者,在瞄準點(基於vehicle_sightings表seenDate領域。這段代碼是否實現了我想要的?

SELECT 
    sighting_id 
FROM 
    vehicle_sightings 
     INNER JOIN 
    vehicle_vrn ON vehicle_sightings.plate = vehicle_vrn.vrnno 
     INNER JOIN 
    vehicle_ownership ON vehicle_vrn.fk_sysno = vehicle_ownership.fk_sysno 
WHERE 
    vehicle_sightings.seenDate >= vehicle_ownership.ownership_start_date 
     AND (vehicle_sightings.seenDate <= vehicle_ownership.ownership_end_date 
     OR vehicle_ownership.ownership_end_date IS NULL 
     OR vehicle_ownership.ownership_end_date = '0001-01-01 00:00:00') 
GROUP BY sighting_id 
    HAVING seenDate >= MAX(ownership_start_date); 

我已經嘗試了上述查詢的許多變體,但是除了上面粘貼的結果之外,他們似乎都沒有達到預期的結果,但是我擔心的是它並不是我想要的,因爲我沒有太多的關於GROUP BY陳述的經驗

我想要的是,在下面的截圖中,ownership_start_dateseenDate最接近的記錄被使用,而ot她被忽略了。另外,在指定了end_date的情況下,這些並不重要。此場景僅在沒有指定end_date的情況下存在,並且有多個歷史記錄。

我在正確的軌道上嗎?這個查詢是否有意義?是否也需要考慮vehicle_vrn的歷史數據,因爲也可能會出現同一個vrn有多個條目但具有不同vrn_start_dates的情況。

enter image description here

+0

對不起,我的英語。但目擊意味着「被看到」?您可以使用模式準備http://sqlfiddle.com/嗎? –

+0

我嘗試閱讀您的問題的其餘部分,並不清楚您想要什麼。你需要包含一個更大的樣本數據,並根據這些數據來解釋期望的結果。還需要包含你的數據庫模式。 \t請閱讀[**如何提問**](http://stackoverflow.com/help/how-to-ask) \t \t這裏是[** START **]( http://spaghettidba.com/2015/04/24/how-to-post-at-sql-question-on-a-public-forum/)瞭解如何提高您的問題質量並獲得更好的答案。 –

回答

1

你幾乎沒有。但是,您的HAVING條款不會產生任何影響(每個組中最新的ownership_start_date必須在seenDate之前,因爲您已明確要求WHERE條款中的每個組成記錄)。

您所追求的是group-wise maximum,可以通過將分組結果返回到基礎表格來獲得。例如:

SELECT * FROM vehicle_ownership JOIN (
    SELECT 
     vehicle_sightings.*, 
     vehicle_ownership.fk_sysno, 
     MAX(vehicle_ownership.ownership_start_date) AS ownership_start_date 
    FROM 
     vehicle_sightings 
      INNER JOIN 
     vehicle_vrn ON vehicle_sightings.plate = vehicle_vrn.vrnno 
      INNER JOIN 
     vehicle_ownership ON vehicle_vrn.fk_sysno = vehicle_ownership.fk_sysno 
    WHERE 
     vehicle_sightings.seenDate >= vehicle_ownership.ownership_start_date 
      AND (vehicle_sightings.seenDate <= vehicle_ownership.ownership_end_date 
      OR vehicle_ownership.ownership_end_date IS NULL 
      OR vehicle_ownership.ownership_end_date = '0001-01-01 00:00:00') 
    GROUP BY sighting_id 
) t USING (fk_sysno, ownership_start_date) 
+0

感謝您的建議。我以前從未見過「使用」聲明 - 它是否有助於實現我所追求的目標? –

+0

@DotNET:'a JOIN b USING(col)'基本上是'a JOIN b ON a.col = b.col'的簡寫(除非沒有表格限定符的'col'在結果中不會含糊不清)。正如我的回答所解釋的,什麼能幫助你實現你所追求的目標,即把分組結果加入到'vehicle_ownership'表中。 – eggyal

+0

太好了,我會試試!它是否也適合車輛的歷史價值?除了採用最接近於seenDate的vehicle_start_date之外,它還需要取vrn500的值,其vrn_start_date最接近seenDate –