总和函数问题PostgreSQL 9.4.5

时间:2018-06-28 16:52:29

标签: sql database postgresql postgresql-9.4

我正在执行一个查询,该查询对数据库的某些值进行求和,该列的数据类型为实数,但是它向我显示了不带小数部分的结果,我想知道是什么问题,因为我有很多带小数的值。 查询:

select extract(Month from date)||'/'|| extract(Year from date) as month_year, 
sum(value) as total
from my_sum_table
where extract(Year from date) =2018 and 
extract(Month from date) between 01 and 05 group by extract(Month from 
date),extract(Year from date) order by extract(Month from date)

我明白了:

enter image description here

当我具有这些值时:

enter image description here

2 个答案:

答案 0 :(得分:0)

您的解释中可能缺少某些内容。我刚刚在PostgreSQL 9.4中尝试了您的查询,并且运行正常:

create table my_sum_table (
  date date,
  value real
);

insert into my_sum_table (date, value) values ('2018-01-01', 130.59);
insert into my_sum_table (date, value) values ('2018-01-02', 256.49);
insert into my_sum_table (date, value) values ('2018-02-15', 712.57);

select extract(Month from date)||'/'|| extract(Year from date) as month_year, 
  trunc(sum(value::double precision)::numeric, 2) as total
  from my_sum_table
  where extract(Year from date) =2018 and 
    extract(Month from date) between 01 and 05 group by extract(Month from 
    date),extract(Year from date) order by extract(Month from date);

结果:

month_year                                          total            
---------------------------------------------------------------------
1/2018                                              387.07999        
2/2018                                              712.57001        

仅供参考,结果列total的类型为float4

此外,您将结果月份显示为01/2018而不是1/2018。这意味着您正在后处理结果。似乎在该后处理中存在问题,而不是在PostgreSQL查询中。

答案 1 :(得分:0)

我验证了real可以存储所需的值,因此我缺少小数位数,因此必须更改数据类型。