![](/img/trans.png)
[英]How to return rows from left table where condition on right table true on all row without sub query
[英]Return all rows from LEFT table even no record in RIGHT table and maximum expiry date from RIGHT tables
在此先感謝您的幫助,我是SQL Server的新手,需要您的專家幫助,我想返回LEFT表中的所有值,即使右表中沒有記錄也是如此,並且MAX(MOT Expiry)或MAX(Road Tax)Expiry 。
我嘗試了此查詢,但無法獲得所需的結果
SELECT Vehicle.id,vehicle.registrationMark, vehicle.status, RoadTax.Expiry, MOT.Expiry
FROM Vehicle
LEFT JOIN RoadTax ON Vehicle.id = RoadTax.VehicleID
LEFT JOIN MOT ON Vehicle.id = MOT.VehicleID;
為了清楚起見,請看此示例。 我想從“車輛”表中退回所有車輛的最大TAX和MOT到期時間。 即使在道路稅或MOT表中也沒有車輛記錄。
車輛表
---------------------------------
| ID | RegistrationMark | Status |
---------------------------------
| 1 | ABC | Active |
| 2 | DEF | Active |
| 3 | GHI | Active |
---------------------------------
道路稅表
------------------------------
| ID | VehicleID | Expiry |
------------------------------
| 1 | 1 | 10/10/2013 |
| 2 | 1 | 10/10/2014 |
| 3 | 2 | 20/12/2014 |
------------------------------
MOT表
-------------------------------
| ID | VehicleID | Expiry |
-------------------------------
| 1 | 2 | 25/01/2015 |
-------------------------------
我想要的結果
-----------------------------------------------------------
| ID | RegistrationMark | Status | TaxExpiry | MOTExpiry |
-----------------------------------------------------------
| 1 | ABC | Active | 10/10/2014 | NULL |
| 2 | DEF | Active | 20/12/2014 | 25/01/2015 |
| 3 | GHI | Active | NULL | NULL |
-----------------------------------------------------------
非常感謝你的幫助。
好像您在查詢的正確軌道上—您只需要添加聚合:
SELECT Vehicle.id,vehicle.registrationMark, vehicle.status
, Max(RoadTax.Expiry) as LatestTax_Exp
, Max(MOT.Expiry) as LatestMOT_Exp
FROM Vehicle
LEFT JOIN RoadTax ON Vehicle.id = RoadTax.VehicleID
LEFT JOIN MOT ON Vehicle.id = MOT.VehicleID;
group by vehicle.ID, vehicle.Registrationmark, vehicle.status
或者,如果我誤解了您想要的東西,並且車輛可能具有多個狀態或注冊,請嘗試:
SELECT Vehicle.id,vehicle.registrationMark, vehicle.status
, Max(RoadTax.Expiry) over (partition by Vehicle.ID) as LatestRT_Exp
, Max(MOT.Expiry) over (partition by Vehicle.ID) as LatestMOT_Exp
FROM Vehicle
LEFT JOIN RoadTax ON Vehicle.id = RoadTax.VehicleID
LEFT JOIN MOT ON Vehicle.id = MOT.VehicleID;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.