SQL Query用于获取具有多个条件和AND运算符的记录

时间:2017-07-31 17:02:53

标签: sql sql-server

我想在查询条件中使用条件来检索确切的记录集。 对于例如考虑一个表

Create table TestRecords
(Id int,
CustID int,
Category varchar(max),
CurrentStatus varchar(max)
)

我在表格中插入了以下值。

insert into TestRecords values(1,1001,'A','P');
insert into TestRecords values(2,1001,'B','P');
 insert into TestRecords values(3,1001,'C','P');
insert into TestRecords values(4,1001,'D','P');
insert into TestRecords values(5,1001,'A','F');
insert into TestRecords values(6,1002,'B','P');
insert into TestRecords values(7,1003,'C','P');
insert into TestRecords values(7,1003,'D','P');
insert into TestRecords values(7,1004,'A','P');
insert into TestRecords values(7,1004,'B','P');
insert into TestRecords values(7,1004,'D','P');
insert into TestRecords values(7,1004,'E','P');

如果我想查找客户ID和完全匹配类别的详细信息,那么我应该编写什么查询。对于例如如果我想找到值为1001的客户ID,则类别应为'A',B和C. 我不希望客户ID仅包含A,B或B,C等类别。如果应该满足所有三个类别。即A,B,C

我尝试过的事情

  select * 
  from TestRecords 
  where CustID=1004 
    and CurrentStatus='P' 
    and Category ='A' 
    and Category ='B' 
    and Category ='C'

我不想使用IN条件,因为它将充当逻辑“OR”运算符,即使它的值与类别A,B或B,C或C,A

匹配也会产生

4 个答案:

答案 0 :(得分:1)

根据我的理解,您希望获得具有所有三个类别的currentstatus'P'的userId。

您可以使用聚合执行此操作:

body

答案 1 :(得分:0)

然后你必须列出所有条件。像这样的东西?

SELECT *
FROM TestRecord
WHERE CustID=1004 -- or 1001, your example and your question does not match here
  AND CurrentStatus = 'P'
  AND Category IN ('A', 'B', 'C')
  AND CustID IN (
    SELECT CustID
    FROM TestRecord
    WHERE CurrentStatus = 'P'
    AND Category = 'A'
  )
  AND CustID IN (
    SELECT CustID
    FROM TestRecord
    WHERE CurrentStatus = 'P'
    AND Category = 'B'
  )
  AND CustID IN (
    SELECT CustID
    FROM TestRecord
    WHERE CurrentStatus = 'P'
    AND Category = 'C'
  )

答案 2 :(得分:0)

这可能有效

select * from TestRecords where CustID=1001 and id in (
(select id from TestRecords where category='A') INTERSECT
(select id from TestRecords where category='B')INTERSECT
(select id from TestRecords where category='C'))

答案 3 :(得分:0)

您需要编写外部查询和内部查询。内部查询将获取结果并将其提供给外部查询。

select * from TestRecords where CustID=1001 and id in 
(
   (select id from TestRecords where category='A') 
              INTERSECT
   (select id from TestRecords where category='B')
              INTERSECT
   (select id from TestRecords where category='C')*
)