Take the 2-minute tour ×
Database Administrators Stack Exchange is a question and answer site for database professionals who wish to improve their database skills and learn from others in the community. It's 100% free, no registration required.

I have 5 digits

A,B,C,D,E

Is it possible in SQL to view all the possible Binary combinations for them? (Not the list of 120 possible permutations, just the 32 possible combinations in SQL http://www.mathsisfun.com/binary-combinations.html)

Thus

A   B   C   D   E
1   1   1   1   1
1   1   1   1   0
1   1   1   0   0
1   1   0   0   0
1   1   0   0   0 etc

Thank you

share|improve this question
add comment

1 Answer

up vote 4 down vote accepted
;WITH x AS 
(
  SELECT x FROM (VALUES('0'),('1')) AS y(x)
)
SELECT A = x.x, B = x2.x, C = x3.x, D = x4.x, E = x5.x, 
       [binary] = x.x + x2.x + x3.x + x4.x + x5.x
FROM x
CROSS JOIN x AS x2
CROSS JOIN x AS x3
CROSS JOIN x AS x4
CROSS JOIN x AS x5;

Or, more lazily and less explicitly:

;WITH x AS 
(
  SELECT x FROM (VALUES('0'),('1')) AS y(x)
)
SELECT A = x.x, B = x2.x, C = x3.x, D = x4.x, E = x5.x, 
       [binary] = x.x + x2.x + x3.x + x4.x + x5.x
FROM x, x AS x2, x AS x3, x AS x4, x AS x5;

Results:

A   B   C   D   E   binary
-   -   -   -   -   ------
0   0   0   0   0   00000
0   1   0   0   0   01000
0   0   1   0   0   00100
0   1   1   0   0   01100
0   0   0   1   0   00010
0   1   0   1   0   01010
0   0   1   1   0   00110
0   1   1   1   0   01110
1   0   0   0   0   10000
1   1   0   0   0   11000
1   0   1   0   0   10100
1   1   1   0   0   11100
1   0   0   1   0   10010
1   1   0   1   0   11010
1   0   1   1   0   10110
1   1   1   1   0   11110
0   0   0   0   1   00001
0   1   0   0   1   01001
0   0   1   0   1   00101
0   1   1   0   1   01101
0   0   0   1   1   00011
0   1   0   1   1   01011
0   0   1   1   1   00111
0   1   1   1   1   01111
1   0   0   0   1   10001
1   1   0   0   1   11001
1   0   1   0   1   10101
1   1   1   0   1   11101
1   0   0   1   1   10011
1   1   0   1   1   11011
1   0   1   1   1   10111
1   1   1   1   1   11111
share|improve this answer
1  
Brilliant, thank you!! –  Peter PitLock Sep 12 '13 at 20:33
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.