Find the average of two combined columns in sql(查找sql中两个组合列的平均值)
问题描述
我想找到两列总数的平均值.我想计算 col1 的总数和 col2 的总数,然后找到平均值(它们在多少不同的行中).
I want to find the avg of the total of two columns. I want to count the total of col1 and the total of col2 then find the average(how many different rows they are in).
我设法在这个 sqlfiddle (另见下文)这是最好的方法吗?我最初认为我需要使用 avg 函数,但无法使用它来解决.
I have managed to come up with a solution in the this sqlfiddle (also see below) is this the best way? I initially thought I would need to use the avg function but couldn't work it out using this.
CREATE TABLE test (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
uid INT,
col1 INT,
col2 INT
) DEFAULT CHARACTER SET utf8 ENGINE=InnoDB;
INSERT INTO test (id, uid, col1, col2) VALUES
(1,5,8,12),
(2,1,2,3),
(3,1,2,33),
(4,5,25,50),
(5,5,22,3);
(
SELECT ((sum(col1) + sum(col2))/count(*))
FROM test
WHERE uid=5
)
推荐答案
根据定义,AVG(col1) = SUM(col1)/COUNT(*)
和 AVG(col2) =SUM(col2)/COUNT(*)
,因此 (SUM(col1)+SUM(col2))/COUNT(*)
= AVG(col1) + AVG(col2))
.
By definition, AVG(col1) = SUM(col1)/COUNT(*)
and AVG(col2) = SUM(col2)/COUNT(*)
, therefore (SUM(col1)+SUM(col2))/COUNT(*)
= AVG(col1) + AVG(col2)
.
此外,加法的可交换性给了我们 (SUM(col1)+SUM(col2))/COUNT(*) = SUM(col1+col2)/COUNT(*)
因此 AVG(col1+col2)
.
Also, the commutativity of addition gives us (SUM(col1)+SUM(col2))/COUNT(*) = SUM(col1+col2)/COUNT(*)
and hence AVG(col1+col2)
.
这篇关于查找sql中两个组合列的平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:查找sql中两个组合列的平均值


- 使用 Oracle PL/SQL developer 生成测试数据 2021-01-01
- 在SQL中,如何为每个组选择前2行 2021-01-01
- 如何将 Byte[] 插入 SQL Server VARBINARY 列 2021-01-01
- 以一个值为轴心,但将一行上的数据按另一行分组? 2022-01-01
- 更改自动增量起始编号? 2021-01-01
- 导入具有可变标题的 Excel 文件 2021-01-01
- 如何将 SonarQube 6.7 从 MySQL 迁移到 postgresql 2022-01-01
- 远程 mySQL 连接抛出“无法使用旧的不安全身份验证连接到 MySQL 4.1+"来自 XAMPP 的错误 2022-01-01
- 如何使用 pip 安装 Python MySQLdb 模块? 2021-01-01
- SQL 临时表问题 2022-01-01