首页数据库postgreSql分组统计数据的实现代码

postgreSql分组统计数据的实现代码

时间2024-02-29 14:59:03发布访客分类数据库浏览568
导读:收集整理的这篇文章主要介绍了postgreSql分组统计数据的实现代码,觉得挺不错的,现在分享给大家,也给大家做个参考。 目录1. 背景2. 需求:3. 构建数据4. 需求实现1. 背景...
收集整理的这篇文章主要介绍了postgreSql分组统计数据的实现代码,觉得挺不错的,现在分享给大家,也给大家做个参考。
目录
  • 1. 背景
  • 2. 需求:
  • 3. 构建数据
  • 4. 需求实现

1. 背景

比如气象台的气温监控,每半小时上报一条数据,有很多个地方的气温监控,这样数据表里就会有很多地方的不同时间的气温数据

2. 需求:

每次查询只查最新的气温数据按照不同的温度区间来分组查出,比如:高温有多少地方,正常有多少地方,低温有多少地方

3. 构建数据

3.1 创建表结构:

-- DROP TABLE public.t_temPEratureCREATE TABLE public.t_temperature (	id int4 NOT NULL GENERATED ALWAYS AS IDENTITY,	place_name vArchar NOT NULL,	value float8 NOT NULL,	up_time timestamp NOT NULL,	CONSTRaiNT t_temperature_pk Primary KEY (id));
    -- PermissionsALTER TABLE public.t_temperature OWNER TO postgres;
    GRANT ALL ON TABLE public.t_temperature TO postgres;
    

3.2 造数据

INSERT INTO public.t_temperature (place_name,value,up_time) VALUES ('广州',35,'2020-07-12 15:00:00.000'),('广州',35.9,'2020-07-12 15:30:00.000'),('深圳',30,'2020-07-12 15:30:00.000'),('深圳',31,'2020-07-12 16:30:00.000'),('三亚',23,'2020-07-12 16:30:00.000'),('三亚',21,'2020-07-12 17:30:00.000'),('北极',-1,'2020-07-12 17:30:00.000'),('北极',-10,'2020-07-12 19:30:00.000');
    

4. 需求实现

4.1 需求1的SQL语句

利用了postgreSql的一个函数:ROW_NUMBER() OVER( [ PRITITION BY col1] ORDER BY col2[ DESC ] )

select	*From	(	select		tt.place_name,		tt.value,		tt.up_time,		row_number() over ( partition by tt.place_name	order by		tt.up_time desc) as row_num	from		t_temperature tt) aaawhere	aaa.row_num = 1

效果如下,查出的都是最新的数据:

4.2 需求2的SQL语句

利用了一个case when then else end 用法来统计数量

select	dd.place_name,	sum(case when dd.value = 0 then 1 else 0 end) as 低温天气,	sum(case when dd.value >
     0 and dd.value  25 then 1 else 0 end) as 正常天气,	sum(case when dd.value >
    = 25 then 1 else 0 end) as 高温天气from	t_temperature ddgroup by	dd.place_name

效果如下,因为没有过滤每个地方的最新数据,查出的是所有数据:

用需求1的结果来查询统计:

select	dd.place_name,	sum(case when dd.value = 0 then 1 else 0 end) as 低温天气,	sum(case when dd.value >
     0 and dd.value  25 then 1 else 0 end) as 正常天气,	sum(case when dd.value >
    = 25 then 1 else 0 end) as 高温天气from	(	select		*	from		(		select			tt.place_name,			tt.value,			tt.up_time,			row_number() over ( partition by tt.place_name		order by			tt.up_time desc) as row_num		from			t_temperature tt) aaa	where		aaa.row_num = 1) ddgroup by	dd.place_name

效果如下:

假如再嵌套一个sum统计,就能查出低温天气,正常天气,高温天气分别合计数量是多少了。

over,enjoy!

到此这篇关于postgreSql分组统计数据的文章就介绍到这了,更多相关postgreSql分组数据内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

您可能感兴趣的文章:
  • postgresql使用filter进行多维度聚合的解决方法
  • postgresql 实现取出分组中最大的几条数据
  • PostgreSQL的中文拼音排序案例
  • Postgresql排序与limit组合场景性能极限优化详解
  • PostgreSQL聚合函数的分组排序使用示例

声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!


若转载请注明出处: postgreSql分组统计数据的实现代码
本文地址: https://pptw.com/jishu/633016.html
PostgreSQL入门简介 hashmap和hashtable的应用场景是什么

游客 回复需填写必要信息