如何计算 PostgreSQL 中的布尔值?

Sch*_*ler 5 postgresql postgresql-9.4

如何计数,postgresql 用户表中公共字段的真假如何我试过这个查询

select 
sum(case when false then 1 else 0 end) as false, 
sum(case when true then 1 else 0 end) as true
from  public.user;
Run Code Online (Sandbox Code Playgroud)

但我没有得到任何价值,如果我从查询中删除 public 那么我将得到正确的计数,只有我的值为 true

table : name|   DOB     | public
values : bb | 20/2/1991/| true

op : true = 1 and false  = 0
Run Code Online (Sandbox Code Playgroud)

但是当我公开为假时,我得到了相同的答案

table : name|   DOB     | public
values : bb | 20/2/1991/| false

op : true = 1 and false  = 0
Run Code Online (Sandbox Code Playgroud)

所以有人请帮我解决这个问题

a_h*_*ame 12

使用filter()子句:

select count(*) filter (where "public") as public_count,
       count(*) filter (where not "public") as not_public_count
from  public."user";
Run Code Online (Sandbox Code Playgroud)

请注意,这user是一个保留关键字,您必须使用双引号才能将其用作表名。

以上假设列public的类型为boolean


ype*_*eᵀᴹ 7

FILTER使用CASE表达式或子查询在没有 的旧版本中工作的其他方式:

SUMCASE表达

select
    sum(case when not public then 1 else 0 end) as false,
    sum(case when     public then 1 else 0 end) as true
from 
    public.user;
Run Code Online (Sandbox Code Playgroud)

COUNTCASE表达式(默认ELSE NULL省略)

select
    count(case when not public then 1 end) as false,
    count(case when     public then 1 end) as true
from
    public.user;
Run Code Online (Sandbox Code Playgroud)

SUM将布尔值转换为整数后( TRUE-> 1, FALSE-> 0)

select
    sum((not public)::int) as false,
    sum(     public ::int) as true
from
    public.user;
Run Code Online (Sandbox Code Playgroud)

一个相当模糊的解决方案(使用 3VL 转换FALSENULL
(@Andriy):

select
    count(not public or null) as false,
    count(    public or null) as true
from
    public.user;
Run Code Online (Sandbox Code Playgroud)

稍微更清楚(或更模糊?)3VL 滥用

select
    count(public and null) as false,
    count(public or  null) as true
from
    public.user;
Run Code Online (Sandbox Code Playgroud)

每个计数的子查询

select
    (select count(*) from public.user where not public) as false,
    (select count(*) from public.user where     public) as true
 ;
Run Code Online (Sandbox Code Playgroud)