0

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.

2 Answers 2

3

Seems to be a simple task for ROW_NUMBER, e.g.

WITH cte as
 (
   SELECT *,
      ROW_NUMBER() 
      OVER (PARTITION BY ID
            ORDER BY Valid DESC, YEAR DESC) AS rn
        -- if there are other values besides X you can switch to
        -- ORDER BY CASE WHEN valid = 'X' then 0 ELSE 1 END, YEAR DESC)
   FROM TABLE
 ) 
select * from cte
where rn = 1 

Btw, same logic can be appied to your TOP query

6
  • I believe you would need to order by ID, then Valid and Year. Is that not correct? I know that in SQL server the data tends to be ordered by the clustered key for this particular function, but I haven't been able to find a reference for whether or not the ordering inherently begins with the partition column. I don't believe it does.
    – Sean
    Commented Oct 17, 2019 at 15:49
  • X ? Did you mean valid?
    – Serg
    Commented Oct 17, 2019 at 15:49
  • @SeanBrookins No need to order by ID because it's already partitioned by it, i.e. all rows in the same partition share the same ID.
    – dnoeth
    Commented Oct 17, 2019 at 16:48
  • This Is real close, however I might have over simplified my example. There are other possible values in the valid column besides x and '', but for my purposes I only care about 'X', so ORDER BY won't work here
    – Whistler
    Commented Oct 17, 2019 at 16:51
  • Then order by a CASE WHEN valid = 'X' then 0 ELSE 1 END instead of valid DESC
    – dnoeth
    Commented Oct 17, 2019 at 16:54
1

I like dnoeth's solution.

However, I wonder if this approach is faster than row_number():

select t.*
from t
where t.year = (select coalesce(max(case when t2.valid = 'X' then t2.year end), max(t2.year))
                from t t2
                where t2.id = t.id
               );

This can take advantage of an index on (id, valid, year).

4
  • This is an excellent suggestion. Would it make sense to modify this to a table? e.g. select t.* from t join (select id, coalesce(max(case when t2.valid = 'X' then t2.year end), max(t2.year)) from t t2) t2 on t.id = t2.id
    – Sean
    Commented Oct 17, 2019 at 16:35
  • @SeanBrookins . . . No, that would not make sense and would probably have worse performance than either proposed solution. Commented Oct 17, 2019 at 18:34
  • Haha, okay, then I'm glad that I asked, @GordonLinoff . I imagine it's due to the index leverage but I'm not certain why the second query wouldn't have the same benefit. Thanks for the helpful posts, I've been seeing you all day!
    – Sean
    Commented Oct 17, 2019 at 19:24
  • 1
    @SeanBrookins . . . Aggregation is generally expensive. Commented Oct 17, 2019 at 19:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.