Sql 如果所有行都满足相同的条件,并且只有一行满足相同的条件,则选择行

Sql 如果所有行都满足相同的条件,并且只有一行满足相同的条件,则选择行,sql,Sql,我有一个OrdersDetails表,所以我想根据订单状态获取订单状态,当所有产品都是新产品时,状态是新的,当所有产品都关闭时,状态是关闭的,当某些产品处于挂起状态时,状态是挂起的 OrderId |ProductID |ProductStatus ORDER1 |PRODUCT1 |NEW ORDER1 |PRODUCT2 |PENDING ORDER2 |PRODUCT3 |CLOSED ORDER2 |PRODUCT4

我有一个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

这是一个
分组依据
案例

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;

这是一个
分组依据
案例

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;

假设您永远不会得到混合状态,除非订单处于挂起状态,这应该可以:

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

假设您永远不会得到混合状态,除非订单处于挂起状态,这应该可以:

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

您使用的是哪种SQL?如果您的订单混合了新的和已关闭的?您使用的是哪种SQL?如果您的订单混合了新的和已关闭的?我知道您有347k代表,这应该不会让我感到惊讶,但您键入答案的速度之快从未停止让我感到惊讶。我刚写完
结尾
,你就发了。@JeremyTwFuture。我之前提到过,我在高中上的最有价值的课程是触摸打字。在大学里,我最喜欢的是折纸多面体,但那是另一回事。我知道你有347k的代表,这应该不会让我感到惊讶,但它永远不会停止让我惊讶你打字的速度有多快。我刚写完
结尾
,你就发了。@JeremyTwFuture。我之前提到过,我在高中上的最有价值的课程是触摸打字。在大学里,我最喜欢的是折纸多面体,但那是另一回事。