提前感谢帮我解决这个问题,我是SQL Server的新手,需要你的专业帮助,我想从LEFT表中返回所有值,即使右表中没有记录,MAX(MOT Expiry)或MAX(Road税收到期。
我尝试了此查询,但无法获得所需的结果
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到期。道路税或交通运输表中没有车辆记录。
车辆表
---------------------------------
| 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 |
-----------------------------------------------------------
非常感谢你的帮助。
答案 0 :(得分:0)
看起来你的查询就在你的正确轨道上 - 你只需要添加聚合:
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;