首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >除法的商数?

除法的商数?
EN

Stack Overflow用户
提问于 2014-05-14 19:00:19
回答 2查看 813关注 0票数 2

我试图在select语句中除以两列,然后将商数除以小数点后的4位。

代码语言:javascript
运行
复制
select round(round(sum(case when acct_no = '2999' 
      and date between '1/1/14' and current_date then amount end)::numeric, 4)::float
 / round(sum(case when acct_no = '3989' 
      and date between '1/1/14' and current_date then amount end)::numeric, 4)::numeric, 4) column
from table

查询的其余部分将包含多个日期,因此其中的日期应该是必需的。

它所造成的错误:

错误:函数圆(双精度,整数)不存在。

这是在PostgreSQL中尝试的。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-05-14 19:48:16

我重新格式化了您的示例代码,以尝试更容易地理解它:

代码语言:javascript
运行
复制
select  round(
            round(
                sum(
                    case
                        when    acct_no = '2999'
                                and date between '1/1/14' and current_date then amount
                    end )::numeric,
                4 )::float
            / round(
                sum(
                    case
                        when    acct_no = '3989'
                                and date between '1/1/14' and current_date then amount
                    end )::numeric,
                4 )::numeric,
            4 ) column
from table

问题是,您正在将除法操作的分子转换为float数据类型double precision

代码语言:javascript
运行
复制
round(
    sum(
        case
            when    acct_no = '2999'
                    and date between '1/1/14' and current_date then amount
        end )::numeric,
    4 )::float
/ round(
    sum(
        case
            when    acct_no = '3989'
                    and date between '1/1/14' and current_date then amount
        end )::numeric,
    4 )::numeric

因此,表达式的结果是一个double precision值,而不是numeric值,因此出现了您观察到的错误。

票数 3
EN

Stack Overflow用户

发布于 2014-05-14 20:49:56

代码语言:javascript
运行
复制
SELECT round((
          sum(CASE WHEN acct_no = '2999' 
              AND thedate between '2014-1-1' AND current_date THEN amount END)
        / sum(CASE WHEN acct_no = '3989' 
              AND thedate between '2014-1-1' AND current_date THEN amount END)
       )::numeric, 4) AS result
FROM   tbl;
  • 在Postgres中没有为浮点类型添加精度修饰符的函数round()。只对numeric根据文件
  • 将浮点数除以numeric,得到double precision (float8)。测试: 选择5::浮动/3::数值--结果是双精度
  • 在计算结束时再转一圈。更快更准确。
  • 永远不要使用date作为列名。它是标准SQL中的保留字,在Postgres中是基类型。
  • 最好在代码中使用日期文本中的推荐的ISO 8601日期格式。此操作与设置和区域设置无关,而您的本地格式将与不同的设置中断。

如果不是因为您提到的rest of the query,这可以进一步简化:

代码语言:javascript
运行
复制
SELECT round((   sum(CASE WHEN acct_no = '2999' THEN amount END)
        / NULLIF(sum(CASE WHEN acct_no = '3989' THEN amount END), 0)
       )::numeric, 4) AS result
FROM   tbl
WHERE  thedate between '2014-1-1'::date AND current_date;

最后,在除数上使用NULLIF()捕获“除法为0”的异常。

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23662963

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档