首页 > 解决方案 > 一条记录中的均值、标准和计数

问题描述

我的数据如下所示:

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 添加计数。这真的更有效率吗?还要别的吗?

谢谢您的帮助。

标签: sqlsql-servercountaggregation

解决方案


使用条件聚合

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

推荐阅读