【问题标题】:Mysql query to dynamically count the occurrences of a row and convert it to columnsMysql查询动态计算一行的出现次数并将其转换为列
【发布时间】:2017-12-03 16:07:10
【问题描述】:

我正在查询一个 mysql 数据库来总结测试执行结果。我的数据看起来像这样。

+-+------------+----------------+
id|test_case_id|execution_status
+-+------------+----------------+
1 |     1      |     passed
+-+------------+----------------+
2 |     2      |     failed
+-+------------+----------------+
3 |     2      |     passed
+-+------------+----------------+
4 |     1      |     passed
+-+------------+----------------+
5 |     2      |     failed
+-+------------+----------------+

我如何查询这些数据来得到这个:

+-+------------+------+------
id|test_case_id|passed|failed
+-+------------+------+------
1 |    1       |  2   |  0
+-+------------+------+------
2 |    2       |  1   |  2
+-+------------+------+------

我能找到的最接近的东西是这个帖子:Mysql query to dynamically convert rows to columns。但是,由于我需要总结执行状态的出现,我不能完全让它工作。由于数据源和目标的考虑,我不能使用临时表、动态 SQL 或存储过程。任何帮助表示赞赏!

【问题讨论】:

    标签: mysql sql pivot aggregate-functions


    【解决方案1】:

    我认为您可以使用条件聚合。我不知道你为什么没有在搜索中找到这个:

    select test_case_id, sum(execution_status = 'passed') as passed,
           sum(execution_status = 'failed') as failed
    from t
    group by test_case_id;
    

    【讨论】:

    • 天哪,我把事情弄得太复杂了,却忽略了显而易见的事情。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2013-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-23
    • 2022-01-21
    相关资源
    最近更新 更多