获取具有一个特定值但没有其他特定值的ID

时间:2011-10-10 23:11:44

标签: tsql

我有两列

OrderId  OrderStatus
120      1
120      2
121      1
123      1
123      2

我想只检索具有OrderId 121的行,因为它的OrderStatus为1,但OrderStatus没有为2.

3 个答案:

答案 0 :(得分:2)

因为您没有提及“StatusDate”或类似内容,我将采取

  

我想只返回OrderId 121的行,因为它的OrderStatus为1但是它的OrderStatus为2。

表示

  

我想只带回OrderId 121,因为OrderId 121和OrderStatus 1有一行,但OrderId 121和OrderStatus 2没有行

使用SQL 2005及更高版本,EXCEPT使这非常简洁:

SELECT OrderId FROM [Order] WHERE OrderStatus = 1
EXCEPT
SELECT OrderId FROM [Order] WHERE OrderStatus = 2

EXCEPT returns distinct values因此无需再进一步DISTINCT

答案 1 :(得分:1)

您可以使用自联接,从左侧搜索订单状态= 1,从右侧搜索订单状态= 2的错过联接:

declare @t table(OrderID int, OrderStatus int)
insert into @t values (120, 1)
insert into @t values (120, 2)
insert into @t values (121, 1)
insert into @t values (123, 1)
insert into @t values (123, 2)

select t1.* 
from @t 
    t1 left join 
    (select * from @t where OrderStatus = 2) as t2 on t2.OrderID = t1.OrderID 
where 
    t1.OrderStatus = 1 and
    t2.OrderID is null

答案 2 :(得分:0)

如果您的订单状态仅为1和2,并且订单在成为状态2之前必须在某个时刻处于状态1,您可以搜索最大订单状态值为1的订单:

  select distinct orderid from orders
group by orderid
  having max(orderstatus) = 1;

演示:http://www.sqlize.com/2k3C2SqMH2

或者如果它不那么简单,我们可以通过使用not exists子句更明确地禁止发生2的orderstatus:

select distinct orderid
  from orders o
 where not exists (
     select * from orders o2
     where o2.orderid = o.orderid
       and o2.orderstatus = 2
   );

演示:http://www.sqlize.com/o6fSvWmvaj