我是SQL的新手,从来没有写过任何复杂的查询,我需要帮助。我有下表 -
Platform | TestSuite | TestCase | Status |
-----------|--------------|--------------|-------------|
Win 2012 | TS1 | TC1 | PASS |
Win 2012 | TS1 | TC2 | PASS |
Win 2012 | TS1 | TC3 | FAIL |
Win 2012 | TS1 | TC4 | ABORT |
Win 2012 | TS2 | TC5 | PASS |
Win 2012 | TS2 | TC6 | PASS |
Win 2012 | TS2 | TC7 | FAIL |
Win 2016 | TS1 | TC1 | PASS |
Win 2016 | TS1 | TC2 | PASS |
Win 2016 | TS1 | TC3 | FAIL |
Win 2016 | TS1 | TC4 | ABORT |
Win 2016 | TS2 | TC5 | PASS |
Win 2016 | TS2 | TC6 | PASS |
Win 2016 | TS2 | TC7 | FAIL |
-----------|--------------|--------------|-------------|
我需要编写SQL查询来生成以下结果
Platform | TestSuite | PASS | FAIL | ABORT | TOTAL |
-----------|--------------|----------|---------|----------|-------|
Win 2012 | TS1 | 2 | 1 | 1 | 4 |
Win 2012 | TS2 | 2 | 1 | 0 | 3 |
Win 2016 | TS1 | 2 | 1 | 1 | 4 |
Win 2016 | TS2 | 2 | 1 | 0 | 3 |
答案 0 :(得分:0)
您正在寻找conditional aggregation
。以下是sum
和case
的一种方法,适用于大多数数据库(尽管mysql
支持简写版本):
select platform, testsuite,
sum(case when status = 'pass' then 1 else 0 end) pass,
sum(case when status = 'fail' then 1 else 0 end) fail,
sum(case when status = 'abort' then 1 else 0 end) abort,
count(*) total
from yourtable
group by platform, testsuite
或者因为您使用的是mysql
:
select platform, testsuite,
sum(status = 'pass') pass,
sum(status = 'fail') fail,
sum(status = 'abort') abort,
count(*) total
from yourtable
group by platform, testsuite