SQL GROUP BY和子查询

时间:2018-06-25 09:14:59

标签: sql

OrderHistory Id,IdOrder,状态

和表顺序 OrderId,ConfirmationDate,LastState

OrderHistory示例

1, 1000, 50
2, 1000, 60
3, 1000, 90
4, 1001, 50
5, 1001, 90 

订购

1000, '2018-03-01', 90
1001, '2018-03-01', 90

我会接受所有从未在状态60下通过的订单。 我尝试了很多查询,但仍然可以通过状态60来获得订单。

SELECT oh.idOrdine  
FROM OrderHistory  oh 
where oh.state not in (60) 
and oh.OrderId in (Select OrderID 
                   From Orders 
                   where ConfirmationDate >= '2017-03-01' 
                     and state= 90) 
group by oh.OrderId 
order by oh.OrderId desc


SELECT * 
FROM Orders o 
  join OrderHistory oh on oh.OrderId = o.ORderId 
where o.ConfirmationDate>= '2017-03-01' 
  and o.state= 90 
  and oh.OrderId in (SELECT OrderId 
                     from OrderHistory 
                     WHERE State not in (60) 
                       and State in (95) 
                     group by ORderID) 

怎么了?

3 个答案:

答案 0 :(得分:1)

您应该使用not in而不是Not Exists。通过使用“不在”,您只需消除该行的那一行,而不是所有OrderID的所有行。

SELECT * 
FROM Orders o 
  join OrderHistory oh on oh.OrderId = o.ORderId 
  where o.ConfirmationDate>= '2017-03-01' 
  and o.state= 90 
  and oh.OrderId in (SELECT oh1.OrderId 
                     from OrderHistory oh1
                     WHERE Not Exists (select *
                                       From OrderHistory oh2
                                       where oh2.OrderId=oh1.OrderId and 
                                       oh2.State=60)
                      ) 

答案 1 :(得分:1)

改为使用NOT EXISTS

select o.*
from Orders o
where not exists (select 1 from OrderHistory oh where oh.OrderId = o.OrderId and oh.State = 60);

答案 2 :(得分:0)

如果您只想要具有某种状态的订单,则还可以使用public protocol EventTransmitter { typealias EventCallback = (([Event]) -> Void) func transmit(events: [Event], onSuccess: @escaping EventCallback, onFailure: @escaping EventCallback) } group by

having