2

每個位的位置計數的「1」值數我有我的紅移表BIGINT列,我想那會查詢:在紅移列

  1. 指望有多少次的值「1」出現在此列的所有行跨二進制值每個位的位置
  2. 將顯示它的方式,我就可以拿X頂部bits_positions。

例如(我已經寫了整數值爲二進制簡化的例子):

column 
-------- 
11011110 = 222 
00000000 = 0 
11111100 = 252 
00011000 = 24 
11111100 = 252 
00011000 = 24 
11000010 = 194 

<- bit_position 

將返回象表:

bit_position count 
0    0 
1    2 
2    3 
3    5 
4    5 
5    2 
6    4 
7    4 

在這種情況下我就可以拿到前五名bit_position:(3,4,6,7,2)

注:我最多可以有64個bit_positions一列。

回答

3

您可以使用一個位與&檢查每個位置。

下面是一個例子去跨行:

SELECT SUM(CASE WHEN bit_col & 64 > 0 THEN 1 ELSE 0 END) "1000000" 
    , SUM(CASE WHEN bit_col & 32 > 0 THEN 1 ELSE 0 END) "0100000" 
    , SUM(CASE WHEN bit_col & 16 > 0 THEN 1 ELSE 0 END) "0010000" 
    , SUM(CASE WHEN bit_col & 8 > 0 THEN 1 ELSE 0 END) "0001000" 
    , SUM(CASE WHEN bit_col & 4 > 0 THEN 1 ELSE 0 END) "0000100" 
    , SUM(CASE WHEN bit_col & 2 > 0 THEN 1 ELSE 0 END) "0000010" 
    , SUM(CASE WHEN bit_col & 1 > 0 THEN 1 ELSE 0 END) "0000001" 
FROM my_table 
; 
1000000 | 0100000 | 0010000 | 0001000 | 0000100 | 0000010 | 0000001 
---------+---------+---------+---------+---------+---------+--------- 
     11 |  8 |  11 |  13 |  11 |  9 |  8 

要在一列,你需要使用union結果:

  SELECT 1 AS "col", SUM(CASE WHEN bit_col & 64 > 0 THEN 1 ELSE 0 END) AS bit_count FROM my_table 
UNION ALL SELECT 2 AS "col", SUM(CASE WHEN bit_col & 32 > 0 THEN 1 ELSE 0 END) AS bit_count FROM my_table 
UNION ALL SELECT 3 AS "col", SUM(CASE WHEN bit_col & 16 > 0 THEN 1 ELSE 0 END) AS bit_count FROM my_table 
UNION ALL SELECT 4 AS "col", SUM(CASE WHEN bit_col & 8 > 0 THEN 1 ELSE 0 END) AS bit_count FROM my_table 
UNION ALL SELECT 5 AS "col", SUM(CASE WHEN bit_col & 4 > 0 THEN 1 ELSE 0 END) AS bit_count FROM my_table 
UNION ALL SELECT 6 AS "col", SUM(CASE WHEN bit_col & 2 > 0 THEN 1 ELSE 0 END) AS bit_count FROM my_table 
UNION ALL SELECT 7 AS "col", SUM(CASE WHEN bit_col & 1 > 0 THEN 1 ELSE 0 END) AS bit_count FROM my_table 
ORDER BY bit_count DESC 
; 
position | bit_count 
----------+----------- 
     6 |   6 
     7 |   6 
     4 |   4 
     5 |   4 
     2 |   0 
     3 |   0 
     1 |   0 

http://docs.aws.amazon.com/redshift/latest/dg/r_OPERATOR_SYMBOLS.html

編輯:如果你想您需要使用UDF來研究更動態的東西。你可以從我的f_bitwise_to_string UDF作爲模板開始,並從那裏添加你需要的。 https://github.com/awslabs/amazon-redshift-udfs/blob/master/scalar-udfs/f_bitwise_to_string.sql

+0

感謝joe, 問題是,如前所述,我可能會有多達64位的列,並且我正在尋找更動態的東西(所以它也可以投射超過一列)。 的轉置工會做工作,而且在這種情況下,我找的東西,如果可能的 – JustinCase

+0

更加動感如果您想更多的東西動態,你需要考慮使用UDF。你可以從我的'f_bitwise_to_string' UDF開始作爲模板,並從那裏添加你需要的東西。 https://github.com/awslabs/amazon-redshift-udfs/blob/master/scalar-udfs/f_bitwise_to_string.sql –