Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert bool to int in postgresql [duplicate]

Tags:

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.

like image 630
Daniel L. VanDenBosch Avatar asked May 11 '17 17:05

Daniel L. VanDenBosch


People also ask

Can bool be converted to int?

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.

Is int and integer same in PostgreSQL?

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.

What is the difference between bool and Boolean in PostgreSQL?

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.


2 Answers

Try boolean_col::int:

SELECT item.item_number, SUM(item.item_active::int) FROM  public.item GROUP BY item.item_number; 
like image 119
Gurwinder Singh Avatar answered Oct 07 '22 18:10

Gurwinder Singh


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;
like image 23
Rams Avatar answered Oct 07 '22 18:10

Rams