I'm attempting to pull a report from this table:
CREATE TABLE [Miscellaneous].[BackupStatus](
[BackupStatusId] [int] IDENTITY(1,1) NOT NULL,
[CompanyCode] [varchar](3) NOT NULL,
[ComputerName] [varchar](50) NOT NULL,
[DateTimeOfBackup] [datetime] NOT NULL,
[Description] [varchar](50) NOT NULL,
[IsSuccess] [bit] NOT NULL,
[Message] [nvarchar](max) NOT NULL,
[Exception] [nvarchar](max) NULL,
[ProgramDate] [datetime] NULL,
CONSTRAINT [PK_BackupStatus] PRIMARY KEY CLUSTERED
(
[BackupStatusId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
ALTER TABLE [Miscellaneous].[BackupStatus] ADD CONSTRAINT [DF_BackupStatus_IsSuccess] DEFAULT ((0)) FOR [IsSuccess]
GO
I need to get a list of most recent backup by CompanyCode. I only want the most recent record for each company (ie CompanyCode). I believe that I need to sort the table decending and distinct but I cannot figure it out.
SELECT Distinct CompanyCode, ComputerName, DateTimeOfBackup,
[Description], IsSuccess, [Message],
[Exception], ProgramDate, BackupStatusId
FROM Miscellaneous.BackupStatus
ORDER BY DateTimeOfBackup DESC
I'm getting back all records still. How do I tell the query to use distinct on only one field?
UPDATE
I hope to add some clarity to what I need.
In this case, it should only return records 4262 and 4266, since they are the most recent unique for that CompanyCode.