我如何 select 区分在 SQL 中同时具有 'S' 和 'P' 属性的客户?

How do I select distinct customers who have both attributes 'S' and 'P' in SQL?

在 SQL table 中,我有两个字段:CustomerID 和 TransactionType。 CustomerID 是一个唯一的编号,可以在每笔交易中重复。每笔交易要么 'S' 要么 'P'.

我想 select 在 SQL 中同时具有 'S' 和 'P' 的不同客户 ID。所以在 table 以上我的预期 return 值是 100 和 102。我该怎么做?

您可以为此使用聚合:

select customerid
from your_table
where transactionType in ('S', 'P')
group by customerid
having count(distinct transactionType) = 2;

如果交易类型只能是'S'或'P'(甚至不能为null),您可能会丢失where子句。