gpt4 book ai didi

sql - 选择多个 COUNT

转载 作者:行者123 更新时间:2023-12-04 14:13:07 25 4
gpt4 key购买 nike

在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 调用?

最佳答案

您可以使用 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 聚合将忽略任何为 null 的参数,使用相同的技巧来获取平均值。

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

关于sql - 选择多个 COUNT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18537643/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com