SQL query to retrieve conditional field value

I have a table of data (attached) which is a list of VisitID's with restraint orderdate, RenewalDate ,StopDate and DischDate.

I compute the interval in hours from the previous renewal order until the new renewal date until there is a stop order for each VisitID.

Sometimes the StopDate is not input.  What I want to do is show the interval from the last Renewal Date until the StopDate.  If there is not a Stop Date, then the interval will be from the Last RenewalDate until the DischDate.  If there is no DischDate then the interval is from the last RenewalDate until the Date & Time the query is processed.

How can I do this?

Thanks

Glen
Renewal-Stop.xlsx
GPSPOWAsked:
Who is Participating?

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

x
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.

Mark BullockQA EngineerCommented:
Try this. The last column is the interval in hours. The other columns are so you can see the calculations.
select visitid,  max(renewaldate) last_renewal
, max(stopdate) stop, max(dischdate) discharge
, getdate() processed
, case when max(stopdate) is not null then max(stopdate)
       else case when max(dischdate) is not null then max(dischdate)
                 else getdate()
  end end  as enddate
, datediff(hour, max(renewaldate),
  case when max(stopdate) is not null then max(stopdate)
       else case when max(dischdate) is not null then max(dischdate)
                 else getdate()
  end end ) intervalhours
from visits
group by visitid;

Open in new window


You can see it and try it in sql fiddle http://sqlfiddle.com/#!3/2cb33/1

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
GPSPOWAuthor Commented:
Perfect.

Thanks

Glen
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
Microsoft SQL Server 2008

From novice to tech pro — start learning today.