简体   繁体   中英

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. 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 . 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. 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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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