首页 > 解决方案 > SQL 查询以检索同时存在两个代码的记录

问题描述

如何返回存在 2 个代码的行?

例如:我需要在一个表中搜索客户,我的代码同时存在“A”和“B”(这些代码存在于名为 customer_code 的列中)。

 Customer ---> 123456
 Customer_code ---> A
 Customer_code ---> B

然后我的查询应该返回客户“123456”。

标签: sql

解决方案


用于WHERE过滤 A 和 B。执行GROUP BY. 用于HAVING确保有两个不同的代码。

select customer
from tablename
where customer_code in ('A', 'B')
group by customer
having count(distinct customer_code) = 2

或者,使用INTERSECT

select customer from tablename where customer_code = 'A'
intersect
select customer from tablename where customer_code = 'B'

推荐阅读