Is there a way to get the total number of 1's in a Postgres "bit string" type?
A:
The one / first bit? Or the total number of bits flipped on? The former: bit mask (& 1) the bit. The latter: A nasty query, like:
SELECT (myBit & 1 + myBit >> 1 & 1 + myBit >> 2 & 1) AS bitCount FROM myBitTable;
I suppose, you could also cast to a string and count the 1's in PL/SQL.
Pestilence
2009-12-15 21:05:43
total number of bits flipped on. Casting to a strings seems epically non-performant. I suppose I could write a function to handle the series of bits (I don't know enough PL/SQL to know whether I can easily loop over bitsize and extract the result)
Yehuda Katz
2009-12-15 21:56:31
Hmmm... it looks like bitmasks are *already* strings internally, so maybe that solution isn't as bad as it looks.
Yehuda Katz
2009-12-15 21:57:59
+2
A:
# select length(replace(x::text, '0', '')) from ( values ('1010111101'::bit varying) ) as something(x);
length
--------
7
(1 row)
And approach without string conversion:
# select count(*) from ( select x, generate_series(1, length(x)) as i from ( values ('1010111101'::bit varying) ) as something(x) ) as q where substring(x, i, 1) = B'1';
count
-------
7
(1 row)
depesz
2009-12-15 22:58:18
Pestilence
2009-12-16 19:13:13
+2
A:
If you need it to be really efficient, here's a discussion: Efficiently determining the number of bits set in the contents of, a VARBIT field
Alex Brasetvik
2009-12-16 15:36:09