国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁技術文章
文章詳情頁

mysql如何計算每項權重占比

瀏覽:122日期:2022-06-20 14:33:52

問題描述

有表及數據如下

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

相關文章:
主站蜘蛛池模板: 平凉市| 盐津县| 阳春市| 建始县| 寻乌县| 雷州市| 商河县| 资阳市| 紫阳县| 连江县| 宝山区| 鄄城县| 即墨市| 鸡西市| 玉田县| 柳江县| 安顺市| 明水县| 庆阳市| 博爱县| 元氏县| 筠连县| 健康| 三亚市| 永宁县| 顺昌县| 保山市| 富蕴县| 奉贤区| 合水县| 青川县| 内黄县| 沅陵县| 丹江口市| 天等县| 诸暨市| 中阳县| 江川县| 浮山县| 三门峡市| 苍南县|