Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the relative ratio in rows in mysql

Tags:

mysql

I'm new to MySQL query, so please help me out of this problem, thanks!

I have a table:

query   url   num_clicks
-------------------------
qa      ua    20
qa      ub    30
qa      uc    50
qb      ud    10
qb      ue    90

I would like to calculate the relative ratio according to same query, like:

query   url   num_clicks  ratio
--------------------------------
qa      ua    20          0.2
qa      ub    30          0.3
qa      uc    50          0.5
qb      ud    10          0.1
qb      ue    90          0.9

How can I do it using one query? Thanks!

like image 400
Huang Yen-Chieh Avatar asked Dec 15 '25 08:12

Huang Yen-Chieh


1 Answers

SELECT query,url,num_clicks,num_clicks/t.totalclicks AS ratio
FROM MyTable
INNER JOIN (
   SELECT
   query,SUM(num_clicks) AS totalclicks
   GROUP BY query
) AS t ON MyTable.query = t.query
like image 146
squillman Avatar answered Dec 16 '25 21:12

squillman



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!