1

Im trying to do some conditional queries on Azure SQL, but Im totally lost on how to do it. I have these two tables:

Order Table

OrderID (PK)
...

OrderHistory Table

OrderHistoryId (PK)
OrderId (FK)
DisplayString
OrderStatus

Now what I want to do is join the table OrderHistory to my query, and return a variable based on some conditional queries against OrderHistory

SELECT O.OrderId, [...], Variable
FROM [Order] AS O

-- some code to get "Variable" from OrderHistory

ORDER BY O.OrderId DESC

OFFSET 0 ROWS
FETCH NEXT 200 ROWS ONLY

Conditions

  1. If any of the rows associated with O.OrderId contain %FINISHED% in DisplayString OR OrderStatus = 1; then return 1
  2. If any of the rows associated with O.OrderId contain OrderStatus = 2 AND NOT %FINISHED% in DisplayString; then return 2
  3. If the SUM of all OrderStatus associated with O.OrderId is equal to 0; then return 3

Result

Here's what I want as a result:

OrderId    [...]    Variable
1           ...     1
2           ...     3
3           ...     2
4           ...     2

2 Answers 2

1

User case statement as per the taste of your sql.

Sign up to request clarification or add additional context in comments.

2 Comments

Could you show the OP an example? As it is both CASE and an aggregated query.
An example would be really helpful!
0

This query might need some more work, but it should demonstrate the "case":

select Variable = case when b.DisplayString like 'FINISHED%' or b.OrderStatus = 1
                       then 1
                       else case when b.DisplayString not like 'FINISHED%' and b.OrderStatus = 2
                            then 2
                            else case when c.sumOsStatus = 0 then 3
                            end
                       end
                  end,
* 
from [Order] a
inner join OrderHistory b
    on a.OrderId = b.OrderId
inner join (select OrderId, sum(OrderStatus) sumOsStatus from OrderHistory group by OrderId) c
    on a.OrderId = c.OrderId

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.