Link to home
Start Free TrialLog in
Avatar of ibost
ibost

asked on

Bitwise NOT operator

Hi,
Trying something I thought always worked for me but getting weird results now.

One of the columns in my table is called RefBD (Brain Dead Referrals) and is either 1 or 0.

Select SUM(RefBD) ...  
gives me the total number of records with a 1, aka the total brain dead referrals.  If I have 2000 records and 1500 brain dead referrals then this would return 1500

Select SUM(~RefBD) ...
gives me negative numbers for the result when I expect it to return 500.  I cannot figure why?
According to SQL 2005 BOL:
The ~ bitwise operator performs a bitwise logical NOT for the expression, taking each bit in turn. If expression has a value of 0, the bits in the result set are set to 1; otherwise, the bit in the result is cleared to a value of 0. In other words, ones are changed to zeros and zeros are changed to ones.

I know that I could use
SUM(1 - RefBD) or SUM(RefBD ^ 1)




ASKER CERTIFIED SOLUTION
Avatar of peter57r
peter57r
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of ibost
ibost

ASKER

data type is INT

when i try BIT it says the sum aggregate operation cannot take a bit data type as an argument
Avatar of ibost

ASKER

ahh I think I figured out why it "seemed" to work before... I was always using INTs but anytime I used the ~ operator was in conjunction with an & operator

So usually instead of querying for what I want this time, it would be something like
select sum(RefBD)... [total brain dead referrals]
select sum(RefBD & ~RuleIn)... [total brain dead referrals that were not "rule ins"]

This worked because I was getting the 1 or 0 from the RefBD and then RuleIn was giving a bizarre negative number but the & operator looks at negative numbers as false, therefore it was seeing
(TRUE & FALSE) = 0 and I would get correct totals