I work in PostgreSQL and try to round the average value to three numbers.
I try use round(avg(nubmer),3). But it is don't worked.
I don't use WITH or View, because I do it inside 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
?
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.