MySQL百分比2小数位数

时间:2018-12-23 08:14:47

标签: mysql rounding truncate

使用下面的MYSQL代码,我试图将百分比四舍五入到2位小数,我已经尝试了截断和四舍五入,但是当我将所有百分比从输出中相加时,我并没有得到100%的数字,例如99.9%,99.95 %等

请查看我更新后的完整查询,以同时显示每种类型的计数,不进行四舍五入的百分比和进行四舍五入的百分比:

select
bondtype,
count(distinct secid) AS Count,
concat(count(distinct secid)/(select count(distinct secid) from wca.bond)*100, '%') as Percentage,
concat(ROUND(count(distinct secid)/(select count(distinct secid) from wca.bond)*100, 2), '%') as Percentage_with_Rounding
from wca.bond
group by bondtype;

以下是我得到的输出:

enter image description here

注意,债券类型CS的Percentage_with_Rounding应该为0.05%,而不是0.04%,所有其他计数在四舍五入后看起来都是正确的,但我觉得很奇怪。预先感谢

2 个答案:

答案 0 :(得分:1)

像这样 选择cast(round(((((1 * 100.0)/ 9),2)作为十进制(5,2))

选择 secidtype, ROUND(truncate(concat(count(distsect secid)//(select count(distinct secid)from Securities)* 100.0),2))作为百分比 来自wca.bond 按secidtype分组;

答案 1 :(得分:1)

您不是在以这种方式产生的值“平衡”地计算百分比:

select secidtype, count(DISTINCT secid) from WCA.BOND group by secidtype

可能大于或小于来自另一个表的计数:

select count(distinct secid) from SECURITIES

您可能在一个表中有数百万个表,而在另一个表中只有数个表,根本无法保证这样的一组百分比将增加到100。这是一个示例:

CREATE TABLE bond(
   secid INTEGER  NOT NULL PRIMARY KEY 
   , secidtype integer
);
INSERT INTO bond(secid) 
VALUES 
  (1)
, (2)
, (3)
, (4)
, (5)
, (6)
, (7)
, (8)
, (9)
, (10)
;
CREATE TABLE securities(
   secid INTEGER  NOT NULL PRIMARY KEY 
);
INSERT INTO securities(secid)
VALUES 
  (1)
, (2)
, (3)
;
SELECT 
  coalesce(secidtype,1) secidtype
, count(DISTINCT secid) num_of
, (SELECT count(DISTINCT secid)  FROM securities) other_table
, TRUNCATE (
  CONCAT (
   count(DISTINCT secid) / (
    SELECT count(DISTINCT secid)
    FROM securities
    ) * 100
   , '%'
   )
  , 2
  ) AS Percentage
FROM bond
GROUP BY coalesce(secidtype,1);
secidtype | num_of | other_table | Percentage
--------: | -----: | ----------: | ---------:
        1 |     10 |           3 |     333.33

db <>提琴here