Oracle view to get same value for a field for a given value of another filed

I have an Oracle 11  table Docs with following fields ( and other fields also)

 DocNo   StateNo  Location
  Doc1       10            Loc1
  Doc1       360         Loc2
  Doc1       12            Loc1
  Doc2       1000        Loc3
  Doc2        5             Loc2
  Doc3        360          
  Doc3         5            Loc1
I need a  view with additional field LocationDerived . For a DocNo , look for the highest stateNo and keep that value of location as LocationDerived for  all the rows of the same DocNo (Please note that  null is the LocationDerived for Doc3)
The view should result like this

 DocNo   StateNo  Location   LocationDerived
  Doc1       10            Loc1          Loc2      
  Doc1       360         Loc2           Loc2
  Doc1       12            Loc1          Loc2
  Doc2       1000        Loc3          Loc3
  Doc2        5             Loc2          Loc3                
  Doc2        5             Loc2          Loc3
  Doc3        360                          
  Doc3         5            Loc1
Sam OZAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

select t1.DocNo, t1.StateNo, t1.Location, t3.Location as LocationDerived
from Docs t1 left outer join 
(select  DocNo, max(StateNo) StateNo from Docs  t0 group by  DocNo) t2 on t1.DocNo = t2.DocNo
left outer join Docs  t3 on  t3.DocNo = t2.DocNo and t3.StateNo = t2.StateNo

Open in new window

johnsoneSenior Oracle DBACommented:
No need to hit the table multiple times.
SELECT docno, 
         over ( 
           PARTITION BY docno 
           ORDER BY stateno ROWS BETWEEN unbounded preceding AND unbounded 
FROM   docs; 

Open in new window


Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.