[英]Return all rows from LEFT table even no record in RIGHT table and maximum expiry date from RIGHT tables
thanks in advance to help me out on this, I am new to SQL Server and need your expert help, I want to return all values from LEFT table even no record in right table and MAX(MOT Expiry) or MAX(Road Tax) Expiry. 在此先感谢您的帮助,我是SQL Server的新手,需要您的专家帮助,我想返回LEFT表中的所有值,即使右表中没有记录也是如此,并且MAX(MOT Expiry)或MAX(Road Tax)Expiry 。
I tried this query but cant get the required results 我尝试了此查询,但无法获得所需的结果
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;
For making it clear look at this example. 为了清楚起见,请看此示例。 I want to return all Vehicles from Vehicle table with their max TAX and MOT Expiry. 我想从“车辆”表中退回所有车辆的最大TAX和MOT到期时间。 even a record for a vehicle is not available in Road Tax or MOT Table. 即使在道路税或MOT表中也没有车辆记录。
Vehicle Table 车辆表
---------------------------------
| ID | RegistrationMark | Status |
---------------------------------
| 1 | ABC | Active |
| 2 | DEF | Active |
| 3 | GHI | Active |
---------------------------------
Road Tax Table 道路税表
------------------------------
| ID | VehicleID | Expiry |
------------------------------
| 1 | 1 | 10/10/2013 |
| 2 | 1 | 10/10/2014 |
| 3 | 2 | 20/12/2014 |
------------------------------
MOT Table MOT表
-------------------------------
| ID | VehicleID | Expiry |
-------------------------------
| 1 | 2 | 25/01/2015 |
-------------------------------
Result I want 我想要的结果
-----------------------------------------------------------
| 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 |
-----------------------------------------------------------
Thank you so much for your help. 非常感谢你的帮助。
Seems like you were on the right track with your query - you just need to add the aggregation: 好像您在查询的正确轨道上—您只需要添加聚合:
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
or, if I have misunderstood what you wanted and vehicles can have more than one status or registration, try: 或者,如果我误解了您想要的东西,并且车辆可能具有多个状态或注册,请尝试:
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.