如果找不到状态,如何查询历史记录表?

时间:2018-08-29 14:44:12

标签: sql oracle

我有一个ORDERS表,每个ORDER_ID可以有多个状态。

ORDER_ID |    STATUS
---------|-------------
1001     |    Requested
1001     |     Approved
1001     |     Invoiced
1001     |     Received
1001     |    Delivered
1011     |    Requested
1011     |     Approved
1011     |     Invoiced
1011     |    Delivered

我需要确定已交付ORDER_ID但没有收到STATUS的{​​{1}}。

例如:以下订单没有接收状态。

STATUS

我尝试使用ORDER_ID -------- 1011 进行查询,但是它不起作用 我尝试在内部查询中获取所有状态为group by having count < 5的订单,并尝试获取状态为Delivered而不是Delivered的订单。这也不起作用。类似于

Received

什么是正确的查询?

3 个答案:

答案 0 :(得分:1)

使用条件聚合。

select order_id 
from orders
group by order_id
having count(case when status='Delivered' then 1 end) > 0
and count(case when status='Received' then 1 end) = 0

答案 1 :(得分:0)

Oracle支持MINUS运算符。

SELECT order_id
FROM orders
WHERE status = 'Delivered'
MINUS
SELECT order_id
FROM orders
WHERE status = 'Received'

注意:有人在我之前提供了此答案,但是将其删除了?

答案 2 :(得分:0)

我会使用NOT EXISTS

SELECT o.*
FROM orders o
WHERE STATUS = 'Delivered' AND
      NOT EXISTS (SELECT 1 FROM orders o1 WHERE o1.order_id = o.order_id AND o1.STATUS = 'Received');