我有一个OrdersDetails表,所以我希望根据订单状态获取订单状态,当所有产品都是新产品然后状态是新的,当所有产品都关闭然后状态关闭,当某些产品待处理时状态正在等待。
OrderId |ProductID |ProductStatus
ORDER1 |PRODUCT1 |NEW
ORDER1 |PRODUCT2 |PENDING
ORDER2 |PRODUCT3 |CLOSED
ORDER2 |PRODUCT4 |CLOSED
ORDER3 |PRODUCT5 |NEW
ORDER3 |PRODUCT6 |NEW
ORDER4 |PRODUCT7 |CLOSED
ORDER4 |PRODUCT8 |PENDING
期望的结果表
OrderID |Status
ORDER1 |PENDING
ORDER2 |CLOSED
ORDER3 |NEW
ORDER4 |PENDING
答案 0 :(得分:4)
这是group by
case
:
select orderid,
(case when min(status) = max(status) and min(status) in ('NEW', 'CLOSED')
then min(status)
when sum(case when status = 'PENDING' then 1 else 0 end) > 0
then 'PENDING'
else 'This case is not described in the question'
end)
from t
group by orderid;
答案 1 :(得分:0)
假设你永远不会得到混合状态,除非订单有待处理,这应该有效:
select OrderId, 'PENDING' Status
from #orderTable
group by OrderId
having COUNT(distinct ProductStatus)>1
union all
select OrderId, MIN(ProductStatus) Status
from #orderTable
group by OrderId
having COUNT(distinct ProductStatus)=1
order by 1