【问题标题】:Calculate percentage of subqueries from the same table with group by and having clauses使用 group by 和有子句计算来自同一个表的子查询的百分比
【发布时间】:2021-04-10 05:11:40
【问题描述】:

我正在使用 PostGres 10.12 DB,其中包含有关测试的各种字段:

|test_name|result |report_time|main_version|environment|
|    A    |error  |29/11/2020 |     1      |   john    |
|    A    |failure|28/12/2020 |     1      |   john    |
|    A    |error  |29/12/2020 |     1      |   alice   |
|    B    |passed |30/12/2020 |     2      |   ben     |
|    C    |failure|31/12/2020 |     2      |   alice   |
|    A    |error  |31/12/2020 |     2      |   john    |

我正在尝试计算在同一天运行的所有测试中同时具有“失败/错误”和“通过”结果的测试百分比。

我创建了以下查询:

SELECT s.environment, COUNT(*) AS total, COUNT(*)::float / t.total_tests * 100 as percentage
FROM (
     SELECT test_name, environment
     FROM tests where report_time >= now() - interval '5 day' 
     and main_version='1' and environment='John'
     GROUP BY test_name, environment
     having COUNT(case when result in ('failure', 'error') then 1 else null end) > 0 
     and count(case when result = 'passed' then 1 else null end) > 0
     order by environment asc
) s
CROSS JOIN (
      SELECT COUNT(*) AS total_tests FROM tests where report_time >= now() - interval '5 day' 
      and main_version='1' and environment='John'
) t
GROUP BY s.environment, t.total_tests  

这适用于 单一 环境和版本。当我尝试组合环境时,计数错误。
如何正确计算每天的正确百分比?

【问题讨论】:

  • 样本数据所需的结果会有所帮助。你是什​​么意思“在同一天运行”?您的示例代码中的条件是什么?问题没有提到他们。

标签: sql postgresql count percentage


【解决方案1】:

我正在尝试计算在同一天运行的所有测试中同时具有“失败/错误”和“通过”结果的测试百分比。

我不知道“同一天”指的是什么。样本数据取自五天范围内的数据,所以我可能猜到您的意思。

无论如何,基本思想是使用条件聚合:

SELECT test_name, environment,
       AVG( (result = 'passed')::int ) as passed_ratio,
       AVG( (result in ('failure', 'error') )::int ) as fail_error_ratio
FROM tests 
WHERE report_time >= now() - interval '5 day'  AND
      main_version = '1' AND
      environment = 'John'
GROUP BY test_name, environment;

这会返回 0 到 1 之间的比率。如果您想要 0 到 100 之间的百分比,只需乘以 100。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-09-06
    • 2018-03-24
    • 2016-07-02
    • 2014-03-02
    • 2016-05-09
    • 2013-05-31
    • 2021-09-19
    • 1970-01-01
    相关资源
    最近更新 更多