Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
716 views
in Technique[技术] by (71.8m points)

binary - Counting the same positional bits in postgresql bitmasks

I am trying to count each same position bit of multiple bitmasks in postgresql, here is an example of the problem:

Suppose i have three bitmasks (in binary) like:

011011011100110
100011010100101
110110101010101

Now what I want to do is to get the total count of bits in each separate column, considering the above masks as three rows and multiple columns.

e.g The first column have count 2, the second one have count 2, the third one have count of 1 and so on...

In actual i have total of 30 bits in each bitmasks in my database. I want to do it in PostgreSQL. I am open for further explanation of the problem if needed.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could do it by using the get_bit functoin and a couple of joins:

SELECT sum(bit) FILTER (WHERE i = 0)  AS count_0,
       sum(bit) FILTER (WHERE i = 1)  AS count_1,
       ...
       sum(bit) FILTER (WHERE i = 29) AS count_29
FROM bits
   CROSS JOIN generate_series(0, 29) AS i
   CROSS JOIN LATERAL get_bit(b, i) AS bit;

The column with the bit string is b in my example.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...