SQL Server 的 SQL 语句,从包含 2 次方值和的列中选择条目

标签 sql sql-server t-sql bit-manipulation

我希望为 SQL Server 编写一条 SQL 语句,从包含 2 次方值和 (2^n) 的列中选择条目, 例如我有表xxx:

_________________________________________________________
| id | col_pow |col_pow=sum of element power of 2 (2^n) |
|----|---------|----------------------------------------|
| 1  | 11      |11  = 8+2+1   = 2^3 + 2^1 +2^0          |           
| 2  | 3       |3   = 2+1     = 2^1 + 2^0               |
| 3  | 514     |514 = 512+2   = 2^9 + 2^1               |
| 4  | 49      |49  = 32+16+1 = 2^5 + 2^4 +2^0          |
| 5  | 7       |7   = 4+2+1   = 2^2 + 2^1 +2^0          |
---------------------------------------------------------

前。选择

1) 选择 id 表 xxx,其中 col_pow can_contains 4 (=2^2)

  • 预期结果:
| id |
|----|
| 5  |

2) 选择 id 表 xxx,其中 col_pow can_contains 2 (=2^1)

  • 预期结果:
| id |
|----|
| 1  |
| 2  |
| 3  |
| 4  |
| 5  |

3) 选择 id 表 xxx,其中 col_pow can_contains 512(=2^9)

  • 预期结果:
| id |
|----|
| 3  |

这3条语句怎么写?

最佳答案

如果我理解正确的话,使用 Bitwise AND (&)可能会有所帮助。

表:

CREATE TABLE #Data (
    id int,
    col_pow int
)
INSERT INTO #Data 
    (id, col_pow)
VALUES
    (1, 11),
    (2, 3),
    (3, 514),
    (4, 49),
    (5, 7)

声明:

DECLARE @power int = 9
SELECT *
FROM #Data
WHERE (col_pow & POWER(2, @power)) = POWER(2, @power) 

结果:

id  col_pow
3   514

计算(对于 2^9):

-------|----------------|-----
A      | 0010 0000 0010 | 514
B      | 0010 0000 0000 | 512
-------|----------------|-----
A & B  | 0010 0000 0000 | 512

关于SQL Server 的 SQL 语句,从包含 2 次方值和的列中选择条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58445637/

相关文章:

sql-server - SQL Server 中 varbinary(max) 的最大实际空间

sql - TSQL 在 where 子句中选择最短日期

arrays - T-SQL 解析包含动态值数组的 JSON

SQL Server : error creating table with multiple primary keys

c# - 带引号的标识符 - EF Code First

sql - 授予对 View 的 SELECT 权限,但不授予对基础对象的 SELECT 权限

sql - 在 SQL Server 2008 中沿路径移动点

sql-server - 在远程服务器中执行 xp_cmdshell

sql - DB2 需要有关更改表更改列集数据类型的帮助

mysql - 查询以检查表的平均值,如果大于则返回结果