Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
| Author |
Topic |
|
safecoder@gmail.com
Starting Member
22 Posts |
Posted - 2006-06-07 : 00:33:54
|
| groupies..thanks for ur time on this..but here is my dilemma..need ur valuable suggestion..I have a "vehicle" table and a "status history" table with vehicle ID as a forecign key..Here i need to write a query to fetch all vehicleID's and latest status for that vehicleID from "status history" table..And if the "status history" table doesn't have a partcular vehicleId, i still want to return (vehicleID,NULL)..Here is the query that i'm workig on now..SELECTvehicle.[vehicleID] AS VehicleId ,status.[statusName] AS Status from[Vehicle] vehicle left join statusHistory status onvehicle.VehicleID = status.VehicleIDbut, the problem, is..it is getting all the previous statuses for that VehicleID from history table...so, i added the following condition..SELECTvehicle.[vehicleID] AS VehicleId ,status.[statusName] AS Status from[Vehicle] vehicle left join statusHistory status onvehicle.VehicleID = status.VehicleIDwherestatus.sys_add_tmstmp = ( SELECT MAX(sys_add_tmstmp) FROM statusHistory WHERE vehicleID = @vehicle.VehicleID)but, then..It is giving me a subset of records where VehicleId exists in the history table..Am stuck @ this point...Do, i need to use a CURSOR to get the "LATEST" status for each vehicleID????Any help/pointer/advice will be greatly appreciated..Thanks, |
|
|
khtan
In (Som, Ni, Yak)
17689 Posts |
Posted - 2006-06-07 : 00:39:51
|
Try thisSELECT vehicle.[vehicleID] AS VehicleId , status.[statusName] AS Statusfrom [Vehicle] vehicle left join statusHistory status on vehicle.VehicleID = status.VehicleIDand status.sys_add_tmstmp = ( SELECT MAX(sys_add_tmstmp) FROM statusHistory hist WHERE hist.vehicleID = status.VehicleID) KH |
 |
|
|
safecoder@gmail.com
Starting Member
22 Posts |
Posted - 2006-06-09 : 01:10:20
|
sweet...that works...why didn't i think of this earlier...hmm..thanks a ton for ur time..quote: Originally posted by khtan Try thisSELECT vehicle.[vehicleID] AS VehicleId , status.[statusName] AS Statusfrom [Vehicle] vehicle left join statusHistory status on vehicle.VehicleID = status.VehicleIDand status.sys_add_tmstmp = ( SELECT MAX(sys_add_tmstmp) FROM statusHistory hist WHERE hist.vehicleID = status.VehicleID) KH
|
 |
|
|
|
|
|
|
|