我正在嘗試創建一個查詢來評估特定車輛的所有者是否在某個時間點。車輛的目擊量包含在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_date
與seenDate
最接近的記錄被使用,而ot她被忽略了。另外,在指定了end_date的情況下,這些並不重要。此場景僅在沒有指定end_date的情況下存在,並且有多個歷史記錄。
我在正確的軌道上嗎?這個查詢是否有意義?是否也需要考慮vehicle_vrn
的歷史數據,因爲也可能會出現同一個vrn有多個條目但具有不同vrn_start_dates
的情況。
對不起,我的英語。但目擊意味着「被看到」?您可以使用模式準備http://sqlfiddle.com/嗎? –
我嘗試閱讀您的問題的其餘部分,並不清楚您想要什麼。你需要包含一個更大的樣本數據,並根據這些數據來解釋期望的結果。還需要包含你的數據庫模式。 \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/)瞭解如何提高您的問題質量並獲得更好的答案。 –