gpt4 book ai didi

SQL 率(百分比)计算 - 除以零错误

转载 作者:行者123 更新时间:2023-11-29 14:30:55 28 4
gpt4 key购买 nike

尝试使用 NULLIF 或 IFNULL 函数,但仍收到被零除的消息。

SELECT 
client_id
,COUNT(distinct CASE WHEN status = 'failed' THEN id END) AS count_FAILS
,COUNT(distinct CASE WHEN status = 'completed' THEN id END) AS count_COMPLETED
,COUNT(distinct CASE WHEN status IN ('failed') THEN id END)
/CAST(COUNT(CASE WHEN status = 'completed' THEN id END) AS FLOAT)

FROM journey
GROUP BY 1

示例数据库和查询 https://dbfiddle.uk/?rdbms=postgres_10&fiddle=efc0cd25843e852ab7a3aa8fe49e6986

这样的查询是否需要 distinct?

谢谢!

最佳答案

这应该有效:

COUNT(distinct CASE WHEN status IN ('failed') THEN id END) * 1.0 /
NULLIF(COUNT(CASE WHEN status = 'completed' THEN id END), 0)

您可以转换为 float 。我更喜欢只使用 * 1.0

我注意到 count_completed 的定义使用了 count(distinct),但是这个比率没有。这可能是一个错误。

我更可能想要总体失败状态的比例,而不是比率。如果这是可以接受的并且 COUNT(DISTINCT) 对任何一个计数都不是必需的,那么这可以简化为:

avg( (status = 'failed')::int )

关于SQL 率(百分比)计算 - 除以零错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52016764/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com