Mysql查询动态计算行的出现次数并将其转换为列

时间:2017-12-03 16:07:11

标签: mysql sql pivot aggregate-functions

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

{
    "nodes":[
        {"name":"N1","group":0},
        {"name":"N2","group":0},
        {"name":"N3","group":1},
        {"name":"N4","group":1},
        {"name":"N5","group":1},
        {"name":"N6","group":2},
        {"name":"N7","group":2},
        {"name":"N8","group":2},
        {"name":"N9","group":2},
        {"name":"N10","group":2},
        {"name":"N11","group":3},
        {"name":"N12","group":3},
        {"name":"N13","group":4}
    ],
    "links":[
        {"source":0,"target":4},
        {"source":4,"target":2},
        {"source":2,"target":1},
        {"source":1,"target":6},
        {"source":6,"target":3},
        {"source":3,"target":8},
        {"source":8,"target":9},
        {"source":7,"target":5},
        {"source":5,"target":10}
    ]
}

如何查询此数据以获取此信息:

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

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

1 个答案:

答案 0 :(得分:3)

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

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