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. boot2docker無法啟動(dòng)2. java - SSH框架中寫分頁(yè)時(shí)service層中不能注入分頁(yè)類3. 關(guān)于docker下的nginx壓力測(cè)試4. docker安裝后出現(xiàn)Cannot connect to the Docker daemon.5. 為什么我ping不通我的docker容器呢???6. mac里的docker如何命令行開啟呢?7. node.js - antdesign怎么集合react-redux對(duì)input控件進(jìn)行初始化賦值8. 老師,按tab鍵不起作用怎么回事9. docker鏡像push報(bào)錯(cuò)10. dockerfile - 為什么docker容器啟動(dòng)不了?

網(wǎng)公網(wǎng)安備