Skip to content
Advertisement

Conditionally use CASE…WHEN – Oracle SQL

I have two tables like so:

tblOrders: OrderNo (pk), CurrentStepNo (fk)

tblSteps: StepNo (pk), OrderNo (fk), StepName, StepType, StepStart, StepStop

tblOrders contains tons of information about our sales orders, while tblSteps contains tons of information regarding the proper sequential steps it takes to build the material we are selling.

I am trying to construct a query that follows this logic:

“For all orders, select the current step name from the step table. If the Step Type is equal to ‘XO’, then select the most recently completed (where StepStop is not null) regular step (where StepStop is equal to ‘YY’)”

I have the following query:

Which successfully returns to me the current step name for an in-process order. What I need to achieve is, when the tblOrders.CurrentStepNo is of type 'XO', to find the MAX(tblSteps.StepStop) WHERE tblSteps.StepType = 'YY'. However, I am having trouble putting that logic into my already working query.

Note: I am sorry for the lack of sample data in this example. I would normally post but cannot in this instance. This is also not a homework question.

I have reviewed these references:

Case in Select Statement

https://blogs.msdn.microsoft.com/craigfr/2006/08/23/subqueries-in-case-expressions/

But no luck so far.

I have tried this:

But am struggling to properly formulate the logic

Advertisement

Answer

Join all steps, rank them with ROW_NUMBER, and stay with the best ranked:

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement