在MySQL查询中计算百分比并四舍五入结果
您可以使用CONCAT()和round()。让我们首先创建一个表 –
mysql> create table DemoTable1844
(
Number int,
TotalNumber int
);
Query OK, 0 rows affected (0.00 sec)
使用insert命令在表中插入一些记录 –
mysql> insert into DemoTable1844 values(50,500);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1844 values(80,500);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1844 values(98,500);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1844 values(45,500);
Query OK, 1 row affected (0.00 sec)
使用select语句显示表中的所有记录 –
mysql> select * from DemoTable1844;
这将产生以下输出 –
+--------+-------------+
| Number | TotalNumber |
+--------+-------------+
| 50 | 500 |
| 80 | 500 |
| 98 | 500 |
| 45 | 500 |
+--------+-------------+
4 rows in set (0.00 sec)
以下是在查询中计算百分比并四舍五入结果的查询 –
mysql> select concat(round(((Number / TotalNumber) * 100 ),2), '%') as Result from DemoTable1844;
这将产生以下输出 –
+--------+
| Result |
+--------+
| 10.00% |
| 16.00% |
| 19.60% |
| 9.00% |
+--------+
4 rows in set (0.00 sec)
阅读更多:MySQL 教程