在postgresql中将bool转换为int [duplicate]

时间:2022-03-16 12:40:20

This question already has an answer here:

这个问题在这里已有答案:

I am trying to run the following sql statement.

我试图运行以下sql语句。

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.

我想如果我可以使用函数将item.item_active更改为整数,那么它可以采用活动记录的总和。

2 个解决方案

#1


6  

Try boolean_col::int:

试试boolean_col :: int:

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

#2


2  

If that value you are getting is boolean then you can write case statement to count your active records.

如果您获得的值是布尔值,则可以编写case语句来计算活动记录。

SELECT
item.item_number, SUM(case when item.item_active then 1 else 0 end)
FROM 
public.item
GROUP BY item.item_number;

#1


6  

Try boolean_col::int:

试试boolean_col :: int:

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

#2


2  

If that value you are getting is boolean then you can write case statement to count your active records.

如果您获得的值是布尔值,则可以编写case语句来计算活动记录。

SELECT
item.item_number, SUM(case when item.item_active then 1 else 0 end)
FROM 
public.item
GROUP BY item.item_number;