Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
922 views
in Technique[技术] by (71.8m points)

mysql - Find the average of two combined columns in sql

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).

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
    )
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

By definition, AVG(col1) = SUM(col1)/COUNT(*) and AVG(col2) = SUM(col2)/COUNT(*), therefore (SUM(col1)+SUM(col2))/COUNT(*) = AVG(col1) + AVG(col2).

Also, the commutativity of addition gives us (SUM(col1)+SUM(col2))/COUNT(*) = SUM(col1+col2)/COUNT(*) and hence AVG(col1+col2).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...