gpt4 book ai didi

sql - 从仓库事实表中获取成功/失败率的最佳查询

转载 作者:行者123 更新时间:2023-11-29 12:39:07 25 4
gpt4 key购买 nike

我正在尝试微调查询并希望得到一些反馈。我有一个 job_fact 仓库表,其中包含作业最终事件 (final_event_type) 的度量单位。我正在尝试查询会给我一个成功/失败率的事实。这是我到目前为止所拥有的:

SELECT
CASE WHEN jf.final_event_type IN (4,6,8,9) THEN count(final_event_type) END as num_failures,
CASE WHEN jf.final_event_type IN (5,7,10) THEN count(final_event_type) END as num_successes
FROM job_fact jf
GROUP BY jf.final_event_type;

此查询仅在两行结果中提供原始成功和失败值:

+----------------------+-----------------------+
| num_failures | num_successes |
+----------------------+-----------------------+
| [NULL] | 6 |
| 14 | [NULL] |
+----------------------+-----------------------+

有谁知道是否有办法 a) 在一行中获得结果,以及 b) 能够计算两者之间的比率(例如失败百分比)。我假设有人会告诉我,我最好为此编写一个程序,但我想尽可能避免它。我知道有一种优雅的方法可以做到这一点,但我想我今天缺少 sql-foo。

我正在运行 PostgreSQL 9.0.1。感谢您提供的任何帮助。

更新

根据所选答案(来自@Ronnis),如果您想知道,这是我的最终查询:

select
sum(case when final_event_type in(4,6,8,9) then 1 else 0 end) as failures,
sum(case when final_event_type in(5,7,10) then 1 else 0 end) as successes,
count(final_event_type) as total_events,
sum(case when final_event_type in(4,6,8,9) then 1 else 0 end) / count(final_event_type)::decimal as failure_percentage,
sum(case when final_event_type in(5,7,10) then 1 else 0 end) / count(final_event_type)::decimal as success_percentage
from job_fact;

最佳答案

如果 where final_event_type in(4,5,6,7,8,9,10) 会命中大部分表格,我认为以下代码会非常高效:

select sum(case when final_event_type in(4,6,8,9) then 1 else 0 end) as failures
,sum(case when final_event_type in(5,7,10) then 1 else 0 end) as successes
from job_fact;

编辑
我不知道 postgresq 是如何执行上述查询的。在Oracle中,有一种访问路径叫做Index Fast Full scan,基本上就是把索引当成一张表。没有遍历(慢),只是全扫描(高效)。好处是 {final_event_type} 上的索引比整个表扫描起来要小得多。(我没有提到位图索引,因为那样会更快)。

关于sql - 从仓库事实表中获取成功/失败率的最佳查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5042643/

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