I have the table of DeviceMaster and DeviceStatus.
where in DeviceMaster is the master for devices and the DeviceStatus is the status of the device.Now i want to get the record of the latest DeviceStatus of each device with only one row using the DeviceMasterId and according to the last one first(descending order).
eg.
DeviceName RecordCreatedDate Status
ElectronicRod 14/11/2011 12:00:00 On
ElectronicRod 14/11/2011 11:30:00 Off
even though the there is multiple record in DeviceStatus.
here is the table structure
DeviceMaster
[Id] [int],
[ROId] [int] ,
[ClientId] [int] ,
[DeviceTypeId] [int] ,
[Label] [varchar](50) ,
[ClientCommChannelId] [int] ,
[ServerCommChannelId] [bigint] ,
[DeviceName] [varchar](50) ,
[Address] [varchar](50) ,
[Attribute1] [varchar](50) ,
[Attribute2] [varchar](50) ,
[Attribute3] [varchar](50) ,
[IsDeleted] [bit] ,
[RecordCreatedDate] [datetime] ,
[RecordUpdatedDate] [datetime] ,
[RecordCreatedBy] [int] ,
[RecordUpdatedBy] [int] ,
[IsTransfered] [bit]
DeviceStatus
[Id] [bigint],
[ROId] [int],
[ClientId] [int],
[ServerDeviceId] [bigint] , --It is the foreign key reference of Device Id
[ClientDeviceId] [int] ,
[Status] [bit] ,
[TimeStamp] [datetime] ,
[Attribute1] [varchar](50) ,
[Attribute2] [varchar](50) ,
[Attribute3] [varchar](50) ,
[RecordCreatedDate] [datetime] ,
[RecordUpdatedDate] [datetime] ,
[RecordCreatedBy] [int] ,
[RecordUpdatedBy] [int] ,
[IsTransfered] [bit]
DeviceStatus have the multiple line entry for single device.I need the latest DeviceStatus for each and every device.
Thank you in advance
You can use a CTE (Common Table Expression) with the
ROW_NUMBERfunction:This CTE “partitions” your data by
DeviceMasterId, and for each partition, theROW_NUMBERfunction hands out sequential numbers, starting at 1 and ordered byRecordCreatedDate DESC– so the most recent row getsRowNum = 1(for eachDeviceMasterId) which is what I select from the CTE in the SELECT statement after it.