我试图在Azure SQL上做一些条件查询,但我完全迷失了如何做到这一点。 我有这两个表:
OrderID (PK)
...
OrderHistoryId (PK)
OrderId (FK)
DisplayString
OrderStatus
现在我要做的是将表OrderHistory连接到我的查询,并根据对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
这就是我想要的结果:
OrderId [...] Variable
1 ... 1
2 ... 3
3 ... 2
4 ... 2
答案 0 :(得分:1)
用户case声明,根据你的sql的味道。
答案 1 :(得分:0)
此查询可能需要更多工作,但它应该演示“案例”:
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