2

在 Oracle 中,给定以下数据

+------------+-----+
+ STATUS     | GRP +
+------------+-----+
+ Pass       | A   +
+ Fail       | A   +
+ Pass       | A   +
+ Pass       | B   +
+ Fail       | B   +
+ Pass       | C   +
+ bad        | C   +
+------------------+

我想得到以下结果

+---------+-------+-------+-------+
+ GRP     | Total + Pass  + Fail  +
+---------+-------+-------+-------+
+ A       | 3     + 2     + 1     +
+ B       | 2     + 1     + 1     +
+ C       | 2     + 1     + 0     +
+---------+-------+-------+-------+

是否可以使用一个 SQL 查询来完成,还是需要进行三个单独的 SQL 调用?

4

2 回答 2

10

您可以使用 SQL 分组以及 COUNT() 和 SUM() 聚合函数来执行此操作。对于 SUM,我们使用嵌入式 CASE 语句的标准 SQL“技巧”。

select GRP, COUNT(*) as Total, 
            SUM(CASE WHEN STATUS = 'Pass' THEN 1 ELSE 0 END) AS Pass,
            SUM(CASE WHEN STATUS = 'Fail' THEN 1 ELSE 0 END) AS Fail
from table
group by GRP

平均值 使用相同的技巧来获取平均值,因为知道 AVG 聚合将忽略任何为空的参数。

select GRP, COUNT(*) as Total, 
            SUM(CASE WHEN STATUS = 'Pass' THEN 1 ELSE 0 END) AS Pass,
            SUM(CASE WHEN STATUS = 'Fail' THEN 1 ELSE 0 END) AS Fail,
            AVG(CASE WHEN STATUS = 'Pass' THEN Score ELSE null END) AS PassAVG,
            AVG(CASE WHEN STATUS = 'Fail' THEN Score ELSE null END) AS FailAVG,
from table
group by GRP
于 2013-08-30T16:43:19.897 回答
0

是你要找的吗?

SELECT s.GRP, (SELECT COUNT(*) FROM stats ss WHERE s.GRP = ss.GRP) AS Total,
    (SELECT COUNT(*) FROM stats ss WHERE s.GRP = ss.GRP AND ss.status = 'Pass')
        AS Pass,
    (SELECT COUNT(*) FROM stats ss WHERE s.GRP = ss.GRP AND ss.status = 'Fail')
        AS Fail
FROM stats s GROUP BY GRP;
于 2013-08-30T16:47:02.197 回答