繁体   English   中英

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

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

我正在查询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查询动态地将行转换为列 但是,由于我需要总结执行状态的发生,我无法让它工作。 由于数据源和目标考虑因素,我无法使用临时表,动态SQL或存储过程。 任何帮助赞赏!

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

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