IT

PostgreSQL에서 평균을 소수점 이하 2 자리로 반올림하는 방법은 무엇입니까?

lottoking 2020. 6. 9. 07:50
반응형

PostgreSQL에서 평균을 소수점 이하 2 자리로 반올림하는 방법은 무엇입니까?


Ruby gem 'sequel'을 통해 PostgreSQL을 사용하고 있습니다.

소수점 이하 두 자리로 반올림하려고합니다.

내 코드는 다음과 같습니다.

SELECT ROUND(AVG(some_column),2)    
FROM table

다음과 같은 오류가 발생합니다.

PG::Error: ERROR:  function round(double precision, integer) does 
not exist (Sequel::DatabaseError)

다음 코드를 실행할 때 오류가 발생하지 않습니다.

SELECT ROUND(AVG(some_column))
FROM table

아무도 내가 뭘 잘못하고 있는지 알고 있습니까?


PostgreSQL은 정의하지 않습니다 round(double precision, integer). 의견에서 @Mike Sherrill 'Cat Recall'이 설명하는 이유 때문에 정밀도를 취하는 라운드 버전은에서만 사용할 수 있습니다 numeric.

regress=> SELECT round( float8 '3.1415927', 2 );
ERROR:  function round(double precision, integer) does not exist

regress=> \df *round*
                           List of functions
   Schema   |  Name  | Result data type | Argument data types |  Type  
------------+--------+------------------+---------------------+--------
 pg_catalog | dround | double precision | double precision    | normal
 pg_catalog | round  | double precision | double precision    | normal
 pg_catalog | round  | numeric          | numeric             | normal
 pg_catalog | round  | numeric          | numeric, integer    | normal
(4 rows)

regress=> SELECT round( CAST(float8 '3.1415927' as numeric), 2);
 round 
-------
  3.14
(1 row)

(위에서, float8는에 대한 축약 형 별칭입니다 double precision. PostgreSQL이이를 출력에서 ​​확장하고 있음을 알 수 있습니다).

numeric2 인수 형식의을 사용하려면 반올림 할 값을 캐스트해야합니다 round. 다음 ::numeric과 같이 속기 캐스팅을 추가하십시오 round(val::numeric,2).


사용자에게 표시 할 형식을 지정하는 경우을 사용하지 마십시오 round. 사용 to_char(참조 : 데이터 유형 포맷 함수 매뉴얼에), 당신은 형식을 지정할 수 있습니다 당신에게주는 text함께 할 수있는 클라이언트 언어 불확실성 어떤 영향을받지 않는 결과 numeric값을. 예를 들면 다음과 같습니다.

regress=> SELECT to_char(float8 '3.1415927', 'FM999999999.00');
    to_char    
---------------
 3.14
(1 row)

to_char서식의 일부로 숫자를 반올림합니다. FM접두사는 이야기 to_char는 선행 공백과 패딩을 싶지 않아.


캐스팅에 대한 이전 구문을 사용해보십시오.

SELECT ROUND(AVG(some_column)::numeric,2)    
FROM table;

PostgreSQL의 모든 버전에서 작동합니다.

일부 PostgreSQL 함수 에는 오버로드가 부족한 이유는 무엇입니까? 왜?

추신 : 반올림에 대한 또 다른 요점은 정확성 입니다. @ IanKenney 's answer 확인하십시오 .


캐스팅 전략으로서의 과부하

다음 과 같이 ROUND 기능을 과부하 시킬 수 있습니다 .

 CREATE FUNCTION ROUND(float,int) RETURNS NUMERIC AS $$
    SELECT ROUND($1::numeric,$2);
 $$ language SQL IMMUTABLE;

이제 명령이 제대로 작동합니다 (함수 생성 후)

 SELECT round(1/3.,4); -- 0.3333 numeric

하지만 NUMERIC 유형을 반환합니다. 첫 번째 commom-usage 과부하를 유지하기 위해 TEXT 매개 변수가 제공 될 때 FLOAT 유형을 반환 할 수 있습니다.

 CREATE FUNCTION ROUND(float, text, int DEFAULT 0) 
 RETURNS FLOAT AS $$
    SELECT CASE WHEN $2='dec'
                THEN ROUND($1::numeric,$3)::float
                -- ... WHEN $2='hex' THEN ... WHEN $2='bin' THEN... complete!
                ELSE 'NaN'::float  -- like an error message 
            END;
 $$ language SQL IMMUTABLE;

시험

 SELECT round(1/3.,'dec',4);   -- 0.3333 float!
 SELECT round(2.8+1/3.,'dec',1); -- 3.1 float!
 SELECT round(2.8+1/3.,'dec'::text); -- need to cast string? pg bug 

추신 : \df round과부하 후 점검 하면 다음과 같이 표시됩니다.

스키마 | 이름 | 결과 데이터 유형 | 인수 데이터 유형
------------ + ------- + ------------------ + ---------- ------------------
 미스 테마 | 라운드 | 배정도 | 배정도, 텍스트, int
 미스 테마 | 라운드 | 숫자 | 배정도, int
 pg_catalog | 라운드 | 배정도 | 배정도            
 pg_catalog | round | numeric          | numeric   
 pg_catalog | round | numeric          | numeric, int          

The pg_catalog functions are the default ones, see manual of build-in math functions.


Try with this:

SELECT to_char (2/3::float, 'FM999999990.00');
-- RESULT: 0.67

Or simply:

SELECT round (2/3::DECIMAL, 2)::TEXT
-- RESULT: 0.67

According to Bryan's response you can do this to limit decimals in a query. I convert from km/h to m/s and display it in dygraphs but when I did it in dygraphs it looked weird. Looks fine when doing the calculation in the query instead. This is on postgresql 9.5.1.

select date,(wind_speed/3.6)::numeric(7,1) from readings;

Error:function round(double precision, integer) does not exist

Solution: You need to addtype cast then it will work

Ex: round(extract(second from job_end_time_t)::integer,0)


you can use the function below

 SELECT TRUNC(14.568,2);

the result will show :

14.56

you can also cast your variable to the desire type :

 SELECT TRUNC(YOUR_VAR::numeric,2)

참고URL : https://stackoverflow.com/questions/13113096/how-to-round-an-average-to-2-decimal-places-in-postgresql

반응형