I am trying to run the following sql statement.
SELECT
item.item_number, SUM(item.item_active)
FROM
public.item
GROUP BY item.item_number;
I am returning the following error:
ERROR: function sum(boolean) does not exist
I figure if I can use a function to change the item.item_active
to an integer, then it can take the sum of the active records.
Bool is a datatype in C++, and we can use true or false keyword for it. If we want to convert bool to int, we can use typecasting. Always true value will be 1, and false value will be 0.
There are three kinds of integers in PostgreSQL: Small integer ( SMALLINT ) is 2-byte signed integer that has a range from -32,768 to 32,767. Integer ( INT ) is a 4-byte integer that has a range from -2,147,483,648 to 2,147,483,647.
PostgreSQL Boolean is a simple data type that we have used to represent only the structure of true or false data or values. PostgreSQL will support the SQL99 defined Boolean data type of SQL standard; Boolean is also known as “bool”, bool is an alias of Boolean data type in PostgreSQL.
Try boolean_col::int
:
SELECT item.item_number, SUM(item.item_active::int) FROM public.item GROUP BY item.item_number;
If that value you are getting is boolean then you can write case statement to count your active records.
SELECT
item.item_number, SUM(case when item.item_active then 1 else 0 end)
FROM
public.item
GROUP BY item.item_number;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With