3

我使用 pgAdmin 4.. 我试图弄清楚如何对列rental_period 进行舍入,该列是从扣除 2 个时间戳列中提取的,现在由双精度数据类型组成。我想将它四舍五入到小数点后 2 位。这是返回错误的脚本:

SELECT customer_id, ROUND (AVG (extract (day from (return_date - rental_date))), 2) AS rental_period
FROM rental
GROUP BY customer_id;

错误说:

错误:“AS”处或附近的语法错误

第 1 行:...xtract(从(return_date - 出租日期)开始的日期),2)AS 出租_... ^ SQL 状态:42601

性格:84

这是一个运行良好的脚本,但返回的小数位太多:

SELECT customer_id, AVG (extract (day from (return_date - rental_date))) AS rental_period
FROM rental
GROUP BY customer_id;

谢谢)

4

3 回答 3

2

我无法重现您显示的错误,您的实际代码一定存在语法问题。

但是,这会失败(出现不同的错误):

SELECT round(
          EXTRACT(day FROM (DATE '2019-06-30')),
          2
       );
ERROR:  function round(double precision, integer) does not exist
LINE 1: SELECT round(EXTRACT(day FROM (DATE '2019-06-30')), 2);
               ^
HINT:  No function matches the given name and argument types. You might need to add explicit type casts.

原因是没有作为第一个参数的双参数round函数double precision

\df round
                         List of functions
   Schema   | Name  | Result data type | Argument data types | Type 
------------+-------+------------------+---------------------+------
 pg_catalog | round | double precision | double precision    | func
 pg_catalog | round | numeric          | numeric             | func
 pg_catalog | round | numeric          | numeric, integer    | func
(3 rows)

您必须将显式类型转换添加到numeric

SELECT round(
          CAST (
             EXTRACT(day FROM (DATE '2019-06-30'))
             AS numeric
          ),
          2
       );
 round 
-------
 30.00
(1 row)
于 2019-10-11T10:23:47.167 回答
1

尝试转换为十进制类型

AVG cast((extract (day from (return_date - rental_date))) as decimal(10,2)) AS rental_period
于 2019-10-11T10:23:14.880 回答
0

减去两个日期会返回天数之差。那已经是 a numeric,所以没有必要使用extract

SELECT  customer_id
,       ROUND(AVG(return_date - rental_date), 2) AS rental_period
FROM    rentals
GROUP BY
        customer_id

看到它在 rextester 工作。

于 2019-10-11T10:25:25.457 回答