Sql 计数布尔列,并基于布尔列计算另一列的平均值
通过此查询,它将平均所有计算的时间值。有没有一种方法可以让我只知道状态=真的普通人?我尝试添加where子句,但将导致失败和挂起结果为0Sql 计数布尔列,并基于布尔列计算另一列的平均值,sql,postgresql,select,average,Sql,Postgresql,Select,Average,通过此查询,它将平均所有计算的时间值。有没有一种方法可以让我只知道状态=真的普通人?我尝试添加where子句,但将导致失败和挂起结果为0 CREATE TABLE test ( calculate_time int4 NULL, status bool NULL ); INSERT INTO test (calculate_time,status) VALUES (10,true) ,(15,true) ,(20,true) ,(20,true) ,(5,false) ,(1
CREATE TABLE test (
calculate_time int4 NULL,
status bool NULL
);
INSERT INTO test (calculate_time,status) VALUES
(10,true)
,(15,true)
,(20,true)
,(20,true)
,(5,false)
,(10,false)
,(15,false)
,(100,NULL)
,(200,NULL)
,(300,NULL)
;
您似乎理解条件聚合的概念。您也可以使用大小写表达式表示平均值,就像您在select中对其他术语所做的那样:
select
avg(calculate_time) as cal_time,
count(case when status = true then 1 end) as completed,
count(case when status = false then 1 end) as failed,
count(case when status is null then 1 end) as suspended
from test;
这是因为AVG函数与大多数其他聚合函数一样,忽略空值。因此,状态不正确的记录,其计算时间值将被有效忽略,并且不会影响总体平均值
另一方面注意:您可以在Postgres查询中直接使用布尔值,而无需将它们与true进行比较。也就是说,以下两个大小写表达式是等效的,第二个表达式不太简洁:
select
avg(case when status then calculate_time end) as cal_time,
count(case when status then 1 end) as completed,
count(case when not status then 1 end) as failed,
count(case when status is null then 1 end) as suspended
from test;
您似乎理解条件聚合的概念。您也可以使用大小写表达式表示平均值,就像您在select中对其他术语所做的那样:
select
avg(calculate_time) as cal_time,
count(case when status = true then 1 end) as completed,
count(case when status = false then 1 end) as failed,
count(case when status is null then 1 end) as suspended
from test;
这是因为AVG函数与大多数其他聚合函数一样,忽略空值。因此,状态不正确的记录,其计算时间值将被有效忽略,并且不会影响总体平均值
另一方面注意:您可以在Postgres查询中直接使用布尔值,而无需将它们与true进行比较。也就是说,以下两个大小写表达式是等效的,第二个表达式不太简洁:
select
avg(case when status then calculate_time end) as cal_time,
count(case when status then 1 end) as completed,
count(case when not status then 1 end) as failed,
count(case when status is null then 1 end) as suspended
from test;
除了@Tim的答案之外,从Postgres 9.4开始,您可以向聚合函数调用添加一个筛选子句,这可能会为您节省编写自己的case表达式的时间:
avg(case when status = true then calculate_time end) as cal_time,
avg(case when status then calculate_time end) as cal_time,
除了@Tim的答案之外,从Postgres 9.4开始,您可以向聚合函数调用添加一个筛选子句,这可能会为您节省编写自己的case表达式的时间:
avg(case when status = true then calculate_time end) as cal_time,
avg(case when status then calculate_time end) as cal_time,
我现在试着记住这个+1。我现在试着记住这个+1。