mysql如何計算每項權重占比
問題描述
有表及數據如下
select * from weight_test;+----+------+--------+| id | name | weight |+----+------+--------+| 1 | aaa | 10 || 2 | bbb | 20 || 3 | ccc | 30 || 4 | ddd | 40 |+----+------+--------+
想計算每項的權重占比
#嘗試一 失敗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 |+--------+--------------+
只有第三種這一種方式嗎?有沒更簡單的方式?
問題解答
回答1:SELECT weight,weight/(select sum(weight) from weight_test) from weight_test;
回答2:把my.ini中的sql_mode=only_full_group_by這個去掉再嘗試第一個吧
回答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 |+--------+-------------+
相關文章:
1. android - 分享到微信,如何快速轉換成字節數組2. javascript - 能否讓vue-cli的express修改express重啟服務3. 解決Android webview設置cookie和cookie丟失的問題4. angular.js - Beego 與 AngularJS的模板格式沖突,該怎么解決?5. javascript - vue2.0中,$refs對象為什么用駝峰的方式獲取不到屬性?6. node.js - npm一直提示proxy有問題7. html5 - 有人做過防微信app界面的H5 demo嗎?8. javascript - 有沒有iOS微信中可以在背景播放視頻的方法?9. 最新版本的微信web開發者工具必須要APPID,會提供測試號,但是像你一樣tabBar配置的話不會顯示首頁與日志,難道我要下載跟你一樣的版本?10. Navicat for mysql 中以json格式儲存的數據存在大量反斜杠,如何去除?
