简体   繁体   English

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

[英]Mysql query to dynamically count the occurrences of a row and convert it to columns

I am querying a mysql database to summarize test execution results. 我正在查询mysql数据库以总结测试执行结果。 My data looks something like this. 我的数据看起来像这样。

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

How do I query this data to get this: 如何查询此数据以获取此信息:

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

The closest I could find something is this thread: Mysql query to dynamically convert rows to columns . 我能找到的最接近的东西是这个线程: Mysql查询动态地将行转换为列 However, since I need to sum the occurrences of execution status, I can't quite get it to work. 但是,由于我需要总结执行状态的发生,我无法让它工作。 I cannot use a temporary table, dynamic SQL, or stored proc due to data source and destination considerations. 由于数据源和目标考虑因素,我无法使用临时表,动态SQL或存储过程。 Any help appreciated! 任何帮助赞赏!

I think you can use conditional aggregation. 我认为你可以使用条件聚合。 I don't know why you didn't find this in your searches: 我不知道为什么你在搜索中找不到这个:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM