postgresql按照逗号分割字段,并统计数量和求和
postgresql按照逗号分割字段,并统计数量和求和
sql
SELECT
ucd, p ,tm, step, unitcd, tm_end
from
resource_calc_scene_rain_bound_value_plus
where scprod_id = 13529
ORDER BY ucd asc
postgresql中字段p字段存储的数据为0.0,0.0,0.0,0.0,0.0,0.2,0.0,0.0,0.4,0.7,1.0,1.1,1.1,1,sql语句实现按照逗号分割,统计p的数量,并对p求和,在原来sql基础上增加输出两列pcount和psum。
要在PostgreSQL中修改您的SQL查询,使其能够统计p字段中逗号分隔的值的数量(pcount)和对这些值求和(psum),您可以使用string_to_array函数和unnest函数。以下是修改后的SQL语句:
sql
SELECT
ucd,
p,
tm,
step,
unitcd,
tm_end,
array_length(string_to_array(p, ','), 1) AS pcount,
(SELECT SUM(CAST(trim(value) AS float))
FROM unnest(string_to_array(p, ',')) AS value) AS psum
FROM
resource_calc_scene_rain_bound_value_plus
WHERE
scprod_id = 13529
ORDER BY
ucd ASC
这个查询做了以下操作:
使用string_to_array(p, ',')将逗号分隔的字符串转换为数组
使用array_length()函数获取数组长度作为pcount
使用子查询和unnest()函数展开数组,然后对每个值进行求和计算psum
保留原始查询的所有其他字段和排序
注意:如果p字段中的某些值可能有空格,我添加了trim()函数来确保正确处理。