atlantis
atlantis

Reputation: 837

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!

Upvotes: 1

Views: 380

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1269953

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;

Upvotes: 3

Related Questions