sql - SQL 查询以检索同时存在两个代码的记录
问题描述
如何返回存在 2 个代码的行?
例如:我需要在一个表中搜索客户,我的代码同时存在“A”和“B”(这些代码存在于名为 customer_code 的列中)。
Customer ---> 123456
Customer_code ---> A
Customer_code ---> B
然后我的查询应该返回客户“123456”。
解决方案
用于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'
推荐阅读
- r - 我的 R 代码中用于模型选择的这些方括号是什么意思?
- autohotkey - 有没有办法让 AHK 左键单击,然后按住右键单击 30 秒并重复?
- bash - 没有这样的文件或目录,但文件存在
- c# - 跨两个字符串之间的多行替换文本段 - 正则表达式
- kubernetes - 离线安装 K3S 失败并出现错误:正在启动 kubernetes:准备服务器:构建 kine:拨号 tcp\\:未知网络 tcp\\"
- java - 在 Liferay 7.x 中替换 renderRequest.getParameter("param")
- c# - 使用 Entity Framework Core 3.1.2.0 过滤非空时“SQL 树中的空类型映射”
- javascript - jQuery:使用选择的颜色更改鼠标移动上 div 的背景颜色
- html - 如何使用 CSS 在 div 的边框上实现这种效果?
- mongodb - MongoError: E11000 使用数组对象收集重复键错误