I am trying to write a query that will return
- The most recent AccountDate with a record of 0 on the location identifier
- Then the second most recent account for each location identifier. The entry can be 1 or 0.
- If there are two accounts with the same date, then return the last AccountDate based on DateAccountLoaded
Be that as it may, my solution does not look very elegant. Has anyone got a better way to achieve this.
See below my solution
CREATE TABLE [dbo].[TopTwoKeyed]( ID INT IDENTITY(1,1) PRIMARY KEY(ID), [LocationID] [int] NULL, [AccountDate] [date] NULL, [Record] [tinyint] NULL, [DateAccountLoaded] [date] NULL ) INSERT INTO [dbo].[TopTwoKeyed] ( [LocationID], AccountDate, Record, DateAccountLoaded ) VALUES(1,'2009-10-31',0,'2011-03-23'), (1,'2008-10-31',1,'2011-03-23'), (1,'2008-10-31',0,'2010-03-22'), (1,'2008-10-31',1,'2009-03-23'), (1,'2011-10-31',1,'2010-03-22'), (1,'2009-10-31',0,'2010-03-23'), (2,'2011-10-31',0,'2010-03-23'), (2,'2010-10-31',0,'2010-03-23'), (2,'2010-10-31',1,'2010-03-23'), (2,'2010-10-31',1,'2009-03-23'), (3,'2010-10-31',0,'2010-03-23'), (3,'2009-10-31',0,'2010-03-23'), (3,'2008-10-31',1,'2010-03-23')