1

I am migrating old data into a new database structure and I need to find out the total int of 3 BIT fields in SQL.

So for example,

(Col A = 1, Col B = 2, Col C = 4)

Col A, Col B, COL C
 0      0       0   = 0
 1      0       0   = 1 
 0      1       0   = 2
 0      0       1   = 4
 1      1       1   = 7

I have tried in SQL

SELECT Col A & 1, Col B & 2 

But not entirely sure if that logic will work..

Thanks in advance

2
  • I beleive colB = 4 should be colC = 4 Commented Oct 23, 2014 at 12:49
  • 2
    I advise against this. While it seems like a cool trick, it is going to use more space and also not allow indexes on the data. If the goal is to not keep adding bit columns as new true/falses are tracked, I recommend having one field whose value represents the data name and another that represents the value (So, Male and 1, or Mexican and 0, or Human and 1 could be stored within the same two columns) Commented Oct 23, 2014 at 12:49

1 Answer 1

3

Just multiply the columns by their respective powers of 2. Assuming that ColA is the least significant bit:

SELECT ColA + ColB * 2 + ColC * 4 FROM MyTable;

SqlFiddle

Sign up to request clarification or add additional context in comments.

1 Comment

Thats simple to some, but not to me, hitting the binary and floating point books. thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.