I have a situation where I have a table with multiple entries per entity, from different point in time, so I need to be able to select the most current record that is valid. There is also a Validity flag on each row. So the logic I am trying to achieve is as Follows
1.Get all records tied to a specific key field
2.Return the row that is marked as valid
3.If there is no row that is valid, then return the row with the highest date.
ID DataPoint Shift Valid Year
------------ ----------- -------- ------- --------
A43659 776 1 2019
A43659 777 3 X 2018
A43659 778 1 2017
C43649 300 1 2019
C43649 538 1 2018
C43649 690 2 2016
Given this data the final result should be
ID DataPoint Shift Valid Year
------------ ----------- -------- ------- --------
A43659 777 3 X 2018
C43649 300 1 2019
Now doing this for one item at a time would be relatively easy
IF (SELECT COUNT(*) FROM TABLE WHERE ID = 'A43659' AND Valid = 'X') > 0 BEGIN
SELECT * FROM TABLE WHERE ID = 'A43659' AND Valid = 'X'
END
ELSE
SELECT TOP 1 * FROM TABLE WHERE ID = A43659 ORDER BY YEAR DESC
However I can't figure out a good way to do this without a major case of RBAR (or in this case I guess it's Row By Agonizing Group? RBAG?)
I've been trying to come up with a way to do this using over|partition by
but since my actual data has many data points I haven't found an example that preserves the entire row.