【问题标题】:Average value for Money DatatypeMoney 数据类型的平均值
【发布时间】:2015-12-21 07:22:42
【问题描述】:

以下是“pc”表,其中包含有关 pc 的详细信息。

user=> SELECT * FROM pc;
 code |  model   | speed | ram  |  hd  | cd  |  price  
------+----------+-------+------+------+-----+---------
  101 | Imac     |  2000 | 4096 |  500 | 16x | ₹550.00
  102 | G450     |  1500 | 2048 |  500 | 8x  | ₹450.00
(2 rows)
user=>

现在我想取价格的平均值。于是尝试了以下方法。但它会产生错误。

user=> SELECT AVG(price) FROM pc;
ERROR:  function avg(money) does not exist
LINE 1: SELECT AVG(price) FROM pc;
               ^
HINT:  No function matches the given name and argument types. You might need to add explicit type casts.
user=>

那么,获取货币数据类型中价格列的平均值的方法是什么。

【问题讨论】:

  • 这是我发现 money 数据类型完全没用的原因之一。

标签: sql regex postgresql average postgresql-8.4


【解决方案1】:
SELECT AVG(price::numeric) FROM pc;

根据 PostgreSQL 8 .4 的 Monetary Types

select avg(regexp_replace(price::text, '[$,]', '', 'g')::numeric) from pc

【讨论】:

  • 不,它会产生与 Rahul Tripathi 答案相同的错误。
  • PostgreSQL 8.4.3 on i486-pc-linux-gnu,由 GCC gcc-4.4.real (Ubuntu 4.4.3-4ubuntu5) 4.4.3 编译,32 位
  • @mrg 只需执行select price::numeric from pc limit 2 并回复
  • @mrg 你可以试试这个select avg(regexp_replace(price::text, '[$,]', '', 'g')::numeric) from pc ??
  • 是的。正则表达式生效...谢谢您的帮助。
【解决方案2】:

您需要先删除卢比符号 ( ₹ )。

How do I remove the first characters of a specific column in a table?

在那之后SELECT AVG(price::numeric) FROM pc; 这个查询工作正常。

或者你可以试试:

SELECT AVG(RIGHT(price,-1)::numeric) FROM pc;

【讨论】:

    【解决方案3】:

    AVGsmallint, int, bigint, real, double precision, numeric, or interval 作为参数,根据您的表格,您似乎没有将其存储为其中之一。

    要么将值转换为其中任何一个,要么更改列数据类型以在 postgresql 中使用 AVG。

    http://www.postgresql.org/docs/current/static/functions-aggregate.html

    【讨论】:

    • 即使在从货币转换为其他数据类型时会产生错误。
    • 因为您的字符串值中有 ₹.. 字符串替换可以工作
    【解决方案4】:

    您可以尝试使用正则表达式。 而不是SELECT AVG(price) FROM pcprice 替换为regexp_replace(price::text, '[$,]', '', 'g')::numeric

    【讨论】:

      【解决方案5】:

      你可以这样做:

      SELECT AVG(price::money::numeric::float8) FROM pc;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-03-02
        • 2021-11-18
        • 2019-10-09
        • 1970-01-01
        • 1970-01-01
        • 2021-12-22
        • 2018-07-14
        相关资源
        最近更新 更多