应用场景
使用group by后需要对数据分组后以分组形式展示,然后还需要对数据去重并获得不重复的值的个数
但是还需要算出有几个,因为统计的是有多少天在下雨,现在查到的是哪一天
array_to_string(array_agg( to_char(detection_time, ‘dd’)), ‘,’) AS rainday : 统计下雨的天数, to_char(detection_time, ‘dd’) 将日期转换为当月的日数, DISTINCT 去重, array_agg 将所有日数聚合为一个数组, array_to_string 将数组转换为逗号分隔的字符串。
这时候查询的数据是有重复的**(统计都有哪几天下雨),我们只需要在to_char前加上DISTINCT** 就可以去除重复
完整SQL
( SELECT COUNT(*) * 5 AS rainFallTime,array_to_string(array_agg(DISTINCT to_char(detection_time, 'dd')), ',') AS rainday,
SUM(rainfall) AS rainFall,date_trunc('month', detection_time) AS month
FROM road_environment_info
WHERE
observation_point_id = 32
AND detection_time BETWEEN '2020-04-01' AND '2023-11-01'
AND rainfall IS NOT NULL
AND rainfall != 0
GROUP BY
date_trunc('month', detection_time)
ORDER BY
month
)
到这拿到就是不重复的所有值,但是还需要算出有几个,因为统计的是有多少天在下雨,现在查到的是哪一天
思路:以上面的查询作为子查询,在外层嵌套查询使用array_length(string_to_array(a.rainday, ‘,’), 1) AS rainDayCount计算下雨天数的数量。
具体解释如下:
完整SQL
SELECT a.rainFallTime,a.rainFall,a.month,array_length(string_to_array(a.rainday, ','), 1) AS rainDayCount
FROM
( SELECT COUNT(*) * 5 AS rainFallTime,array_to_string(array_agg(DISTINCT to_char(detection_time, 'dd')), ',') AS rainday,
SUM(rainfall) AS rainFall,date_trunc('month', detection_time) AS month
FROM road_environment_info
WHERE
observation_point_id = 32
AND detection_time BETWEEN '2020-04-01' AND '2023-11-01'
AND rainfall IS NOT NULL
AND rainfall != 0
GROUP BY
date_trunc('month', detection_time)
ORDER BY
month
) AS a
GROUP BY
a.rainFallTime, a.rainFall, a.month,a.rainday
ORDER BY
a.month