-3

I needed some help in making sure I am using my parenthesis correctly around AND OR statements in SQL SERVER.

SELECT DISTINCT *
FROM Table
WHERE yearmonth = 201404
 AND (HasA = 1 OR HasB = 1 OR hasC = 1)
 AND (HasAX = 10 OR HasBX = 10 OR HasCX = 10)

When I have my parenthesis like above my second AND line of code, it also pulls out other values like example HasCX= 23.

Ironically this line of code works well:

AND (HasA = 1 OR HasB = 1 OR hasC = 1)

How should I write my parenthesis around this ?

AND (HasAX = 10 OR HasBX = 10 OR HasCX = 10)

It should only pull out data for where the condition is met with 10.

jarlh
  • 42,561
  • 8
  • 45
  • 63
data addicted
  • 69
  • 1
  • 11

2 Answers2

1

I think your query is right. Check your data. A row can have HasCx=23 but also have HasBX=1.

Brian White
  • 1,265
  • 1
  • 10
  • 16
1

First, for your query, a cleaner way to write the logic is to use in:

SELECT DISTINCT *
FROM Table
WHERE yearmonth = 201404 AND
      1 IN (HasA, HasB, HasC) AND
      10 IN (HasAX, HasBX, HaxCX)

I suspect that what you really want is:

WHERE yearmonth = 201404 AND
      ((HasA = 1 AND HasAZ = 10) OR
       (HasB = 1 AND HasBZ = 10) OR
       (HasC = 1 AND HasCZ = 10)
      )

Alternatively, you might want all of these connected by AND and not OR.

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
  • Thank you, however it is still giving my other products. Let me explain. I have the HasA OR HasB OR HasC as a way pull out customers that have either one of the products. I cannot use AND after each HasA and HasB and HasC as it will pull out all customers that had all three products. The selection of HasAZ and so is because they have to be on a specific platform, let's say Fiber. Even with your code, It still is picking out coax. – data addicted May 22 '15 at 11:14