troubleshooting Question

Bitwise NOT operator

Avatar of ibost
ibost asked on
Microsoft SQL ServerSQL
4 Comments1 Solution277 ViewsLast Modified:
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)




Join the community to see this answer!
Join our exclusive community to see this answer & millions of others.
Unlock 1 Answer and 4 Comments.
Join the Community
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 4 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros