简体   繁体   English

使用 postgresql 根据条件计算速率

[英]Calculate rate based on condition using postgresql

I want to find the rate of negative and zero profits from a column.我想从列中找到负利润和零利润的比率。 I tried to do it using aggregate and subquery but it doesn't seem to work as both method return 0 values.我尝试使用聚合和子查询来做到这一点,但它似乎不起作用,因为这两种方法都返回 0 值。 The code is as follows代码如下

SELECT
COUNT(CASE WHEN profit < 0 THEN 1
    END) AS negative_profits,
COUNT(CASE WHEN profit < 0 THEN 1
    END) / COUNT(profit),
COUNT(CASE WHEN profit = 0 THEN 1
    END) AS zero_profits,
COUNT(CASE WHEN profit = 0 THEN 1
    END) / COUNT(profit)
FROM sales;

SELECT (SELECT COUNT(*)
FROM sales
WHERE profit <= 0)/COUNT(profit) AS n_negative_profit
FROM sales;

Both query return 0 in values enter image description here两个查询都在值中返回 0 在此处输入图像描述

Because you are doing integer division per docs Math operators/functions .因为您正在按照文档数学运算符/函数进行 integer 除法。

numeric_type / numeric_type → numeric_type numeric_type / numeric_type → numeric_type

Division (for integral types, division truncates the result towards zero)除法(对于整数类型,除法会将结果截断为零)

So:所以:

select 2/5; 
0 

You need to make one of the numbers float or numeric :您需要将其中一个数字设为floatnumeric

select 2/5::numeric;  
0.40000000000000000000

and to make it cleaner round:并使其更干净:

select round(2/5::numeric, 2);
0.40

Avoid integer division , which truncates (like Adrian pointed out).避免integer 除法,它会截断(就像阿德里安指出的那样)。
Also, simplify with an aggregate FILTER expression:此外,使用聚合FILTER表达式进行简化:

SELECT count(*) FILTER (WHERE profit <= 0)::float8
     / count(profit) AS n_negative_profit
FROM   sales;

If profit is defined NOT NULL , or to divide by the total count either way, optimize further:如果profit定义为NOT NULL ,或者除以总计数,进一步优化:

SELECT count(*) FILTER (WHERE profit <= 0)::float8
     / count(*) AS n_negative_profit
FROM   sales;

See:看:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM