Pivot Integer Bitwise Values in SQL

元气小坏坏 提交于 2020-01-06 09:04:53

问题


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.


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/9507635/pivot-integer-bitwise-values-in-sql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!