mysql如何計(jì)算每項(xiàng)權(quá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 |+--------+--------------+
只有第三種這一種方式嗎?有沒更簡(jiǎn)單的方式?
問題解答
回答1:SELECT weight,weight/(select sum(weight) from weight_test) from weight_test;
回答2:把my.ini中的sql_mode=only_full_group_by這個(gè)去掉再嘗試第一個(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. python - 獲取到的數(shù)據(jù)生成新的mysql表2. javascript - js 對(duì)中文進(jìn)行MD5加密和python結(jié)果不一樣。3. mysql里的大表用mycat做水平拆分,是不是要先手動(dòng)分好,再配置mycat4. window下mysql中文亂碼怎么解決??5. sass - gem install compass 使用淘寶 Ruby 安裝失敗,出現(xiàn) 4046. python - (初學(xué)者)代碼運(yùn)行不起來,求指導(dǎo),謝謝!7. 為啥不用HBuilder?8. python - flask sqlalchemy signals 無法觸發(fā)9. python的文件讀寫問題?10. 為什么python中實(shí)例檢查推薦使用isinstance而不是type?
