统计所有,并统计单个查询中满足子句的记录

Count all and count the records that meet a clause in a single query

我有一个 table 看起来像这样:

ID | NetAmount | PaymentAmount
1    2.99        1.99
2    2.99        2.99

我想计算 table 中的所有记录,然后将该数字除以 NetAmount-PaymentAmount > 0 的记录数。我该如何实现?

(本例中的结果为 1/2 => 0.5)

最简单的方法使用avg():

select avg(case when netamount > paymentamount then 1.0 else 0.0 end) as ratio
from t;

您可以使用条件聚合:

SELECT 1.0 *
       COUNT(*) /
       COUNT(CASE WHEN NetAmount > PaymentAmount THEN 1 END)
FROM yourdata

1.0 * 部分将确保您得到一个小数结果,其中 0 后有 1 位数字。

使用IIF条件:

SELECT AVG(IIF(NetAmount > PaymentAmount, 1.0, 0.0)) as Result
FROM tableName;