In SQL Server 2005, given the following resultset
ID | InstanceNumber | IsArchived
5000 | 1 | True
8347 | 2 | True
9343 | 3 | False
11048 | 4 | False
What I would like to return is this:
ID | InstanceNumber | IsArchived
9343 | 1 | False
11048 | 2 | False
where the rows with "IsArchived" that is false are returned, but subtracting the max InstanceNumber column from the resultset.
Here is an example SQL statement that returns the behavior I'm looking for:
DECLARE @tbl TABLE
(ID INT NOT NULL, InstanceNumber INT NOT NULL, IsArchived BIT NOT NULL)
INSERT INTO @tbl VALUES (5000, 1, 1)
INSERT INTO @tbl VALUES (8347, 2, 1)
INSERT INTO @tbl VALUES (9343, 3, 0)
INSERT INTO @tbl VALUES (11048, 4, 0)
SELECT ID, InstanceNumber - (SELECT MAX(InstanceNumber) FROM @tbl WHERE IsArchived = 1), IsArchived
FROM @tbl
WHERE IsArchived = 0
Is this the most efficient way to do this or is there another way that this same behavior can be achieved? I have additional where clauses that need to go into the full statement (like 5-6 statements) and I want to avoid having to declare them 2X, once for returning the max instance that's archived, and for the resultset filtering.
EDIT To clarify the requirement of the query, the column "InstanceNumber" could skip numbers. so there could be a record for InstanceNumber = 6 without returning one for 5, so not all records returned will be sequential.