mysql如何計(jì)算每項(xiàng)權(quán)重占比
問(wèn)題描述
有表及數(shù)據(jù)如下
select * from weight_test;+----+------+--------+| id | name | weight |+----+------+--------+| 1 | aaa | 10 || 2 | bbb | 20 || 3 | ccc | 30 || 4 | ddd | 40 |+----+------+--------+
想計(jì)算每項(xiàng)的權(quán)重占比
#嘗試一 失敗select weight, weight/sum(weight) from weight_test;ERROR 1140 (42000): In aggregated query without GROUP BY, expression #1 of SELECT list contains nonaggregated column ’test.weight_test.weight’; this is incompatible with sql_mode=only_full_group_by#嘗試二 失敗select weight, weight/sum(weight) from weight_test group by weight;+--------+--------------------+| weight | weight/sum(weight) |+--------+--------------------+| 10 | 1.0000 || 20 | 1.0000 || 30 | 1.0000 || 40 | 1.0000 |+--------+--------------------+#嘗試三 成功select weight, weight/total from weight_test a, (select sum(weight) total from weight_test) b;+--------+--------------+| weight | weight/total |+--------+--------------+| 10 | 0.1000 || 20 | 0.2000 || 30 | 0.3000 || 40 | 0.4000 |+--------+--------------+
只有第三種這一種方式嗎?有沒(méi)更簡(jiǎn)單的方式?
問(wèn)題解答
回答1:SELECT weight,weight/(select sum(weight) from weight_test) from weight_test;
回答2:把my.ini中的sql_mode=only_full_group_by這個(gè)去掉再?lài)L試第一個(gè)吧
回答3:set @sum = (select sum(weight) from weight_test);select @sum;+------+| @sum |+------+| 100 |+------+select weight, weight/@sum from weight_test;+--------+-------------+| weight | weight/@sum |+--------+-------------+| 10 | 0.1000 || 20 | 0.2000 || 30 | 0.3000 || 40 | 0.4000 |+--------+-------------+
相關(guān)文章:
1. 在mac下出現(xiàn)了兩個(gè)docker環(huán)境2. 如何解決docker宿主機(jī)無(wú)法訪問(wèn)容器中的服務(wù)?3. HTML5不支持frameset一般怎么解決?4. javascript - Vue v-for判斷是否為第4列,然后加個(gè)橫線(xiàn)或者第4行才顯示這一個(gè)<li>5. javascript - react native在run-android時(shí)出現(xiàn)這個(gè)錯(cuò)誤該怎么解決?大神賜教6. javascript - 如何獲取點(diǎn)擊事件點(diǎn)擊后前一個(gè)后一個(gè)的值。7. css3像卷軸一樣展開(kāi)8. docker 下面創(chuàng)建的IMAGE 他們的 ID 一樣?這個(gè)是怎么回事????9. css - 為何box的顏色沒(méi)有變?10. css - C#與java開(kāi)發(fā)Windows程序哪個(gè)好?
