在 postgresql 中将 bool 转换为 int

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43922559/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 02:34:11  来源:igfitidea点击:

Convert bool to int in postgresql

sqlpostgresql

提问by Daniel L. VanDenBosch

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_activeto an integer, then it can take the sum of the active records.

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

回答by Gurwinder Singh

Try boolean_col::int:

尝试boolean_col::int

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

回答by Rams

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;