mysql如何計算每項(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 |+----+------+--------+
想計算每項(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 |+--------+--------------+
只有第三種這一種方式嗎?有沒更簡單的方式?
問題解答
回答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 |+--------+-------------+
相關(guān)文章:
1. 數(shù)組按鍵值封裝!2. angular.js - webpack build后的angularjs路由跳轉(zhuǎn)問題3. java - web項(xiàng)目中,用戶登陸信息存儲在session中好 還是cookie中好,取決于什么?4. 老師,怎么不講一次性添加多個數(shù)據(jù)5. mysql - 查詢字段做了索引為什么不起效,還有查詢一個月的時候數(shù)據(jù)都是全部出來的,如果分拆3次的話就沒問題,為什么呢。6. mysql - 大部分?jǐn)?shù)據(jù)沒有行溢出的text字段是否需要拆表7. pdo - mysql 簡單注入疑問8. Mysql取下一條記錄9. 表格對其 只涉及到對其,沒有涉及到大小,長寬還有背景色類的嗎10. mysql - SQL分組排序、隨機(jī)問題?
