Reputation: 71
Im trying to do some conditional queries on Azure SQL, but Im totally lost on how to do it. I have these two tables:
OrderID (PK)
...
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
Here's what I want as a result:
OrderId [...] Variable
1 ... 1
2 ... 3
3 ... 2
4 ... 2
Upvotes: 1
Views: 107
Reputation: 10209
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
Upvotes: 0