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
- If any of the rows associated with O.OrderId contain %FINISHED% in DisplayString OR OrderStatus = 1; then return 1
- If any of the rows associated with O.OrderId contain OrderStatus = 2 AND NOT %FINISHED% in DisplayString; then return 2
- 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