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. mysql優化 - MySQL如何為配置表建立索引?2. 如何用筆記本上的apache做微信開發的服務器3. 我在網址中輸入localhost/abc.php顯示的是not found是為什么呢?4. 數據庫 - Mysql的存儲過程真的是個坑!求助下面的存儲過程哪里錯啦,實在是找不到哪里的問題了。5. 關于mysql聯合查詢一對多的顯示結果問題6. 冒昧問一下,我這php代碼哪里出錯了???7. windows誤人子弟啊8. php傳對應的id值為什么傳不了啊有木有大神會的看我下方截圖9. MySQL主鍵沖突時的更新操作和替換操作在功能上有什么差別(如圖)10. 實現bing搜索工具urlAPI提交
