排除标准符合的记录

问题描述 投票:1回答:2

我有一组记录,用于识别与客户相关的多个项目。我的困境是,如果客户同时拥有这两个项目,那么我想排除该客户。

如果他们只有一个特定的项目,那么我想包括它。我将使用此代码创建一个视图,所以我试图找到最好的方法。我可以尝试使用Row_number()来识别不同的记录,但我不确定在这种情况下它是否理想。

示例数据表:

Customer | ItemID | value1 | Value2
   A         12       35       0
   B         12       35       0
   C         13       0        25
   C         12       0        25
   D         18       225       12

期望的输出:

 Customer | ItemID | value1 | Value2
   A         12       35       0
   B         12       35       0

这是我到目前为止:

select Customer, ItemID, Value1, Value2
from Table1 
where itemID = 12

这会给我客户'C',我不想要。

sql sql-server row-number
2个回答
1
投票

如果您想要拥有itemid = 12而不是itemid = 13的客户,您可以使用NOT EXISTS

select * from tablename t
where itemid = 12
and not exists (
  select 1 from tablename
  where customer = t.customer
  and itemid = 13
)

如果您想要拥有itemid = 12而不是任何其他itemid的客户:

select * from tablename t
where itemid = 12
and not exists (
  select 1 from tablename
  where customer = t.customer
  and itemid <> 12
)

要么:

select * from tablename
where customer in (
  select customer from tablename
  group by customer
  having min(itemid) = 12 and max(itemid) = 12 
)

1
投票

我想你需要澄清你的问题但是,据我所知,你想要返回所有行:

1)客户有特定项目(即项目ID 12,不包括客户D)

(2)他们只有一个项目,因为他们有两个项目,因此不包括客户C.

如果是这样,那么这就是我所拥有的:

SELECT * 
FROM Table1
WHERE ItemID == '12' AND 
      Customer in (
                   SELECT Customer
                   FROM Table1
                   GROUP BY Customer
                   HAVING Count(Customer) = 1
                  )

编辑:我澄清了我对OP问题的解释。我还在SQL Fiddle(http://sqlfiddle.com/#!5/b5f1f/2/0)上测试了我的解决方案并相应地更新了WHERE子句。

© www.soinside.com 2019 - 2024. All rights reserved.