mysql如何计算每项权重占比
大家讲道理
大家讲道理 2017-04-17 15:03:21
0
3
729

有表及数据如下

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 |
+--------+--------------+

只有第三种这一种方式吗?有没更简单的方式?

大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

全部回覆(3)
伊谢尔伦

從weight_test選擇體重,體重/(從weight_test選擇總和(體重));

伊谢尔伦

把my.ini中的sql_mode=only_full_group_by這個去掉再試試第一個吧

PHPzhong

雷雷

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!