sql - 一条记录中的均值、标准和计数
问题描述
我的数据如下所示:
id res res_q
1 12.9 normal
2 11.5 low
3 13.2 normal
4 9.7 low
5 12.0 low
6 15.5 normal
7 13.5 normal
8 13.3 normal
9 13.5 normal
10 13.1 normal
11 13.4 normal
12 12.9 normal
13 11.8 low
14 11.9 low
15 12.8 normal
16 13.1 normal
17 12.2 normal
18 11.9 low
19 12.5 normal
20 16.5 normal
res_q 可以取值“低”、“正常”和“高”。
我想将它聚合在一条记录中,我将同时拥有 res 的平均值和标准,以及低、正常和高的计数,所有这些都在一条记录中,就像这样
mean sd low normal high
12.9 1.41 6 14 0
当然,我可以通过首先使用 AVG 和 STDEV 聚合平均值和标准,然后使用 COUNT 来获得低/正常/高计数,如下所示:
SELECT AVG(res) AS mean,
STD(res) AS sd,
(SELECT COUNT(1) FROM temp1 WHERE res_q='low') AS low,
(SELECT COUNT(1) FROM temp1 WHERE res_q='normal') AS normal,
(SELECT COUNT(1) FROM temp1 WHERE res_q='high') AS high
FROM temp1
但是,有没有更有效的方法呢?
我能想到的一种可能性是首先使用 AVG 和 STDEV 获取平均值和标准差,然后使用 GROUP BY 获取计数,然后使用 UPDATE 添加计数。这真的更有效率吗?还要别的吗?
谢谢您的帮助。
解决方案
使用条件聚合
SELECT AVG(res) AS mean,
STD(res) AS sd,
count(case when res_q='low' then 1 end) AS low
count(case when res_q='normal' then 1 end) AS normal,
count(case when res_q='high' then 1 end) AS high
FROM temp1
推荐阅读
- mysql - 查询 sql 以与 python 一起使用
- spring - spring-ws .wsdl 不包含 ObjectFactory.class 或 jaxb.index
- c++ - 有没有办法在编译时获取作用域类名?
- c# - 可重用的非捕获组
- android - SoundPool 内存不足?
- flutter - 设置 Flutter bottomNavigationBar 不活动
- python - 使用 Python-Xarray 重新网格化坐标
- javascript - ubuntu 18.04-ember:找不到命令
- javascript - 推入存储在 JavaScript 对象值中的数组的奇怪行为
- ruby-on-rails - json 模板中的子节点