如何输出列使用MySQL划分列的总和

时间:2014-11-06 08:54:57

标签: mysql

下面的示例表

+-------------+-------------+----------+----------+------------------------+
| sourceindex | targetindex | source   | target   | new_count              |
+-------------+-------------+----------+----------+------------------------+
|           0 |           0 | this     | this     |  4.514337716384391e-18 |
|           0 |           1 | this     | is       |  5.501850344983498e-17 |
|           0 |           2 | this     | a        |  5.501850344983498e-17 |
|           0 |           3 | this     | book     |  1.805735523541796e-17 |
|           0 |           4 | this     | ,        |  5.501850344983498e-17 |
|           0 |           5 | this     | that     |  1.805735523541796e-17 |
|           0 |           6 | this     | is       |  5.501850344983498e-17 |
|           0 |           7 | this     | a        |  5.501850344983498e-17 |
|           0 |           8 | this     | pen      |  1.805735523541796e-17 |
|           0 |           9 | this     | .        |  5.501850344983498e-17 |

我希望输出一个列名' prob'等于' new_count' /' new_count'

我是以两种方式做到的,这是错误的

select new_count,new_count/sum(new_count) from EM7;

select
        t1.sourceindex
      , t1.targetindex
      , t1.source
      , t1.target          
      , t1.new_count 
      , t1.new_count/t1.sum(new_count)  as prob
from EM7 t1;

这有什么合适的想法吗?

3 个答案:

答案 0 :(得分:3)

您必须先在子查询中计算总和,然后交叉加入。

SELECT new_count, new_count / sum_new_count
FROM EM7, (
    SELECT SUM(new_count) sum_new_count
    FROM EM7
) sq

答案 1 :(得分:3)

尝试这样的事情: -

SELECT new_count, new_count/(SELECT sum(new_count) FROM EM7) FROM EM7;

答案 2 :(得分:-1)

性能SQL

SELECT new_count, new_count / NEW_TABLE.sum_new_count
FROM EM7
LEFT JOIN (SELECT sourceindex, SUM(new_count) sum_new_count FROM EM7) AS NEW_TABLE 
ON NEW_TABLE.sourceindex = EM7.sourceindex