Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to output a column divide a sum of column using MySQL

Tags:

mysql

the example table below

+-------------+-------------+----------+----------+------------------------+
| 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 |

and i want to output a column name 'prob' which equals to 'new_count'/sum of 'new_count'

i did it in two ways and it was wrong

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

and

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

Is that any suitable thinking??

like image 387
yihang hwang Avatar asked Dec 14 '25 06:12

yihang hwang


2 Answers

Try somthing like this:-

SELECT new_count, new_count/(SELECT sum(new_count) FROM EM7) FROM EM7;
like image 122
Ankit Bajpai Avatar answered Dec 16 '25 23:12

Ankit Bajpai


You have to calculate the total sum first in a subquery and cross join it.

SELECT new_count, new_count / sum_new_count
FROM EM7, (
    SELECT SUM(new_count) sum_new_count
    FROM EM7
) sq
like image 36
fancyPants Avatar answered Dec 16 '25 23:12

fancyPants



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!