如何返回包含2个代码的行?
例如:我需要在一个表中搜索客户,在该表中我的代码同时显示“ A”和“ B”(这些代码显示在名为customer_code的列中)。
Customer ---> 123456
Customer_code ---> A
Customer_code ---> B
然后我的查询应该返回客户“ 123456”。
答案 0 :(得分:0)
使用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'
答案 1 :(得分:0)
这是我用来执行查询的架构:
CREATE TABLE TABLE_NAME
(
Customer long,
Customer_code varchar(30)
);
INSERT INTO TABLE_NAME values(1,'A');
INSERT INTO TABLE_NAME values(2,'A');
INSERT INTO TABLE_NAME values(1,'B');
INSERT INTO TABLE_NAME values(3,'A');
INSERT INTO TABLE_NAME values(3,'B');
我用来获取结果的查询是:
SELECT a.Customer from TABLE_NAME as a,TABLE_NAME as b
WHERE a.Customer_code='A' and b.Customer_code='B'and a.Customer=b.Customer
我得到了结果: 1个 3
因为它们的代码均为'A'和'B'。