简体   繁体   English

SQL 如何将数字四舍五入为三?

[英]SQL how do I round a number to three?

I work in PostgreSQL and try to round the average value to three numbers.我在 PostgreSQL 工作,并尝试将平均值四舍五入为三个数字。

I try use round(avg(nubmer),3).我尝试使用 round(avg(nubmer),3)。 But it is don't worked.但它不起作用。

I don't use WITH or View, because I do it inside function我不使用 WITH 或 View,因为我在 function 中使用

CREATE OR REPLACE FUNCTION sch.show_avg()
    RETURNS TABLE("title" character varying, "mark" numeric) 
    LANGUAGE 'plpgsql'

AS $BODY$

BEGIN
RETURN QUERy
SELECT distinct title,avg(case 
                when mark = '1' then 1::integer
                when mark = '2' then 2::integer
                when mark = '3' then 3::integer
                when mark = '4' then 4::integer
                when mark = '5' then 5::integer
                when mark = '6' then 6::integer
                when mark = '7' then 7::integer
                when mark = '8' then 8::integer
                when mark = '9' then 9::integer
                when mark = '10' then 10::integer
                when mark = '11' then 11::integer
                when mark = '12' then 12::integer
                else 0::integer
                end)
                 over (partition by title) as oc FROM  sch.mark;
END;

$BODY$;

Why wouldn't you write this using group by ?你为什么不使用group by来写这个?

SELECT title,
       AVG(case when mark IN ('1', '2', . . .) then mark::int
                else 0
           end) as oc
FROM  sch.mark
GROUP BY title;

I'm not sure if this fixes your problem, but it is certainly more concise.我不确定这是否能解决您的问题,但它肯定更简洁。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM