Nick Vaccaro
Nick Vaccaro

Reputation: 5504

Pivot Integer Bitwise Values in SQL

Using: SQL Server 2008 R2

My goal is to take a given integer (n) and select every permutation of integers with n bits in 2 columns, as below.

Given: n=4

Output:

ColA  ColB
0     0
0     0
0     0
0     0
1     0
1     0
1     0
1     1
2     0
2     0
2     1
2     0
3     0
3     0
3     1
3     1
...
14    1
14    1
14    1
14    0
15    1
15    1
15    1
15    1

The output does not, repeat does NOT, need to be ordered, which may or may not make this easier. I do, however, need to be able to set n to any integer... but for the sake of runtime, let's say it'll be under 10.

Thanks in advance.

Upvotes: 0

Views: 362

Answers (2)

Nikola Markovinović
Nikola Markovinović

Reputation: 19346

You might want to try this:

declare @bits int
set @bits = 4

;with AllTheNumbers as (
    select cast (POWER(2, @Bits) as int) - 1 Number
    union all
    select Number - 1
    from AllTheNumbers
    where Number > 0
),
Bits as (
    select @Bits - 1 Bit
    union all
    select  Bit - 1
    from Bits
    where Bit > 0
)
select *, case when (Number & cast (POWER(2, Bit) as int)) != 0 then 1 else 0 end
from AllTheNumbers cross join Bits
order by Number, Bit desc

AllTheNumbers produces the numbers from 0 to 2^n-1, Bits produces bit numbers from 0 to @Bits - 1 and main part connects them and calculates bit value per position.

Upvotes: 1

Vince Pergolizzi
Vince Pergolizzi

Reputation: 6584

Let me know if this is ok, when you say 'bits' I assume you mean powers of 2 - so you can specify what power of 2 you want in the set statement and it will return all permutations.

DECLARE @Bit INT
SET @Bit = 4

;WITH NUMS AS (
SELECT TOP(POWER(2,@Bit)+1)ROW_NUMBER() OVER(ORDER BY sc.name) - 1 [N]
FROM syscolumns sc
)

SELECT n1.N, n2.N
FROM NUMS n1
CROSS JOIN NUMS n2
WHERE (n1.N + n2.N) <= POWER(2,@Bit)
ORDER BY n1.N, n2.N

Upvotes: 0

Related Questions