从sql中的每一列减去聚合函数

olmpazwi  于 2021-08-09  发布在  Java
关注(0)|答案(2)|浏览(346)

我正在尝试为sql表的每一列组合来自相应列的聚合函数。例如,如果我想减去每列的平均值,我可以用每列的子查询

SELECT 
       col1 - (SELECT AVG(col1) FROM table), 
       col2 - (SELECT AVG(col2) FROM table),
       col3 - (SELECT AVG(col3) FROM table)
FROM table;

但是,如果表中有许多列,这会很麻烦,需要逐个写入列名。有没有办法简化代码,或者用别名让代码更清晰?

9jyewag0

9jyewag01#

使用窗口功能:

SELECT col1 - AVG(col1) OVER (),
       col2 - AVG(col2) OVER (),
       col3 - AVG(col3) OVER ()
FROM table;
iqih9akk

iqih9akk2#

我想你应该把每个人和所有值的平均值进行比较。

SELECT
t1.uid
t1.col1 - t2.col1avg as col1dev
t1.col2 - t2.col2avg as col2dev
t1.col3 - t2.col3avg as col3dev
FROM
table t1
LEFT JOIN (SELECT
     AVG(col1) as col1avg,
     AVG(col2) as col2avg,
     AVG(col3) as col3avg FROM table) t2 ON ( t1.uid = t2.uid)

相关问题