Question : Retrieve the latest record from the Inner entity of a one to many relationship

Hi experts,

I need some help with an SQL problem.
I have an database that holds information about 'assets' and their 'movements' around the country.
I am trying to retrieve my asset information and just the latest Movement record for that Asset record.

My complete asset information is made up of the following tables:

Asset Table:
AssetId
MachineId
Active
WarrantyExpiry
SerialNo

Machine Table:
MachineId
MachineTypeId
MachineModelId
Active

MachineType Table:      
MachineTypeId
Description

MachineModel Table:      
MachineModelId
Description

I use the following statement to retrieve all the  'asset' information from those tables:

SELECT
Asset.AssetId,
Asset.SerialNo,
MachineType.MachineTypeId,
MachineType.Description AS TypeDesc,
MachineModel.MachineModelId,
MachineModel.Description AS ModelDesc
FROM Asset
INNER JOIN Machine ON Asset.MachineId = Machine.MachineId
INNER JOIN MachineModel ON Machine.MachineModelId = MachineModel.MachineModelId
INNER JOIN MachineType ON Machine.MachineTypeId = MachineType.MachineTypeId
WHERE Asset.Active = 1"

The statement above produces output with the following columns:
AssetId    SerialNo    MachineTypeId    TypeDesc    MachineModelId    ModelDesc



This is the 'movement' table I would like to add to the statement.

Movement Table:      
MovementId
MovementTypeId
FaultTypeId
AssetId
StoreId
RepairHours
RepairCost
MovementDate
Notes

As you can see there is a foreign key on the Movement table for Store (via Storeid) so I also need to get the relevant information from the store table.

Store Table:
StoreId
Active
StoreNo
StoreName
ModifyDate


So the final output will be:

AssetId    SerialNo    MachineTypeId    TypeDesc    MachineModelId    ModelDesc    MovementDate    StoreName

Just to make thing slightly more complicated - if there is no movement I still need to show the Asset.

If you require any further information or clarification please ask :)

Thanks in advance

Answer : Retrieve the latest record from the Inner entity of a one to many relationship


SELECT
Asset.AssetId,
Asset.SerialNo,
MachineType.MachineTypeId,
MachineType.Description AS TypeDesc,
MachineModel.MachineModelId,
MachineModel.Description AS ModelDesc,
x.MovementDate, x.StoreName
FROM Asset
INNER JOIN Machine ON Asset.MachineId = Machine.MachineId
INNER JOIN MachineModel ON Machine.MachineModelId = MachineModel.MachineModelId
INNER JOIN MachineType ON Machine.MachineTypeId = MachineType.MachineTypeId
CROSS APPLY
(
SELECT MAX(MovementDate) MovementDate, MAX(StoreName) StoreName
FROM Store s
JOIN Movement m ON s.StoreID = m.StoreID
WHERE Asset.AssetID = m.AssetID
)x
WHERE Asset.Active = 1
Random Solutions  
 
programming4us programming4us