2位小数

b5lpy0ml  于 2021-06-15  发布在  Mysql
关注(0)|答案(2)|浏览(310)

在下面的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;

下面是我得到的输出:

注意,对于bondtype cs,用四舍五入表示的百分比应该是0.05%,而不是0.04%,所有其他的计数在四舍五入后看起来都是正确的,但只有这个我觉得奇怪。提前谢谢

ctehm74n

ctehm74n1#

您没有以“平衡”的方式计算百分比,此方法产生的值:

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<>在这里摆弄

sq1bmfud

sq1bmfud2#

像这样选择cast(round(((1*100.0)/9),2)作为decimal(5,2))
选择secidtype,round(truncate(concat(count(distinct secid)/(select count(distinct secid)from securities)*100.0),2))作为wca.bond group by secidtype的百分比;

相关问题