选择虚拟列作为百分比

时间:2015-12-29 16:41:14

标签: mysql

有没有办法选择虚拟列作为另一列的百分比,其中最大值为100%的记录?

Example:

+------------------------------+
| tbl_test                     |
+------------------------------+
| id | col_x | value | percent |
+------------------------------+
|  1 |     a |     2 |      25 |
|  2 |     b |     5 |    62.5 |
|  3 |     c |     8 |     100 |
|  4 |     d |     3 |    37.5 |
+------------------------------+

如你所见,8成为100%,其余的计算为8的百分比。

SELECT * , () as percent
FROM tbl_test

2 个答案:

答案 0 :(得分:0)

要做那样的事情,首先需要知道100%是什么:

SELECT MAX(value) AS hperc FROM tbl_test;

一旦知道了,您就可以将其他值除以100%:

SELECT *, value/(SELECT MAX(value) AS hperc FROM tbl_test)*100 AS percent
FROM tbl_test;

答案 1 :(得分:0)

这是在TSQL中完成的方式:

select @max = max(value) from tbl_test
select *, cast(value/@max * 100 as decimal(18,2)) as [percent]
from tbl_test