2

我有下表称为Attributes

* AttId  * CustomerId  * Class * Code *
| 1      | 1           | 1     | AA   |
| 2      | 1           | 1     | AB   |
| 3      | 1           | 1     | AC   |
| 4      | 1           | 2     | AA   |
| 5      | 1           | 2     | AB   |
| 6      | 1           | 3     | AB   |
| 7      | 2           | 1     | AA   |
| 8      | 2           | 1     | AC   |
| 9      | 2           | 2     | AA   |
| 10     | 3           | 1     | AB   |
| 11     | 3           | 3     | AB   |
| 12     | 4           | 1     | AA   |
| 13     | 4           | 2     | AA   |
| 14     | 4           | 2     | AB   |
| 15     | 4           | 3     | AB   |

其中每一个ClassCode配对代表一个特定的Attribute

我正在尝试编写一个返回所有customers未链接到pairingAttribute的查询Class = 1, Code = AB

这将返回Customer Id值 2 和 4。

我开始写Select Distinct A.CustomerId From Attributes A Where (A.Class = 1 and A.Code = 'AB'),但当我意识到我正在写一个SQL查询并且在括号前没有可用于表示不能满足子句的运算符时停止了。

我错过了什么?或者我应该看哪个运营商?

编辑:

我正在尝试编写一个查询,该查询仅返回那些Customers(即不同的客户 ID)Attribute配对没有链接的查询Class = 1, Code = AB

这只能是Customer Id值 2 和 4,因为表不包含行:

* AttId  * CustomerId  * Class * Code *
| x      | 2           | 1     | AB   |
| x      | 4           | 1     | AB   |

将标题更改为:

如何在 Sql Query 中编写“Where Not(a=x and b=x)”

到:

如何编写 Sql 查询以查找从未满足以下“Where Not(a=x and b=x)”的不同值

由于之前的标题本身就是一个问题,但是问题的细节增加了一个额外的维度,导致了混乱。

4

5 回答 5

4

一种方法是

SELECT DISTINCT CustomerId FROM Attributes a 
WHERE NOT EXISTS (
    SELECT * FROM Attributes forbidden 
    WHERE forbidden.CustomerId = a.CustomerId AND forbidden.Class = _forbiddenClassValue_ AND forbidden.Code = _forbiddenCodeValue_
)

或加入

SELECT DISTINCT a.CustomerId FROM Attributes a
LEFT JOIN (
    SELECT CustomerId FROM Attributes
    WHERE Class = _forbiddenClassValue_ AND Code = _forbiddenCodeValue_
) havingForbiddenPair ON a.CustomerId = havingForbiddenPair.CustomerId
WHERE havingForbiddenPair.CustomerId IS NULL

根据 ypercube 的回答,另一种方法是使用 EXCEPT

于 2013-01-02T15:47:11.843 回答
3

由于没有人发布简单的逻辑语句,这里是:

select . . .
where A.Class <> 1 OR A.Code <> 'AB'

(X and Y) 的负数是 (not X or not Y)。

我明白了,这是一个分组的事情。为此,您使用聚合并具有:

select customerId
from Attributes a
group by CustomerId
having sum(case when A.Class = 1 and A.Code = 'AB' then 1 else 0 end) = 0

我总是更喜欢使用这种技术来解决“是否在一组”类型的问题。

于 2013-01-02T15:55:08.193 回答
3
SELECT CustomerId 
FROM Attributes

EXCEPT

SELECT CustomerId 
FROM Attributes
WHERE Class = 1
  AND Code = AB ;
于 2013-01-02T15:59:01.607 回答
1
Select Distinct A.CustomerId From Attributes A Where not (A.Class = 1 and A.Code = 'AB')
于 2013-01-02T15:44:02.300 回答
0

试试这个:

SELECT DISTINCT A.CustomerId From Attributes A Where 
0 = CASE 
         WHEN A.Class = 1 and A.Code = 'AB' THEN 1 
         ELSE 0 
END

编辑:当然,这仍然给你 cust 1(doh!),你应该理想地使用 pjotrs NOT EXISTS 查询,因为我没有足够仔细地查看数据:)

于 2013-01-02T15:47:26.287 回答