Converting bool to int in postgresql

I am trying to run the following SQL query.

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 suppose if I can use a function to change item.item_active

to an integer then it can take the sum of active records.

+3


source to share


2 answers


Try boolean_col::int

:



SELECT
item.item_number, SUM(item.item_active::int)
FROM 
public.item
GROUP BY item.item_number;

      

+4


source


If the value you get is a boolean, you can write a case register to count 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;

      

0


source







All Articles