目錄
- 1. 背景
- 2. 需求:
- 3. 構建數據
- 4. 需求實現
1. 背景
比如氣象臺的氣溫監控,每半小時上報一條數據,有很多個地方的氣溫監控,這樣數據表里就會有很多地方的不同時間的氣溫數據
2. 需求:
每次查詢只查最新的氣溫數據按照不同的溫度區間來分組查出,比如:高溫有多少地方,正常有多少地方,低溫有多少地方
3. 構建數據
3.1 創建表結構:
-- DROP TABLE public.t_temperature
CREATE 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)
);
-- Permissions
ALTER 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) aaa
where
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 dd
group 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) dd
group by
dd.place_name
效果如下:

假如再嵌套一個sum統計,就能查出低溫天氣,正常天氣,高溫天氣分別合計數量是多少了。
over,enjoy!
到此這篇關于postgreSql分組統計數據的文章就介紹到這了,更多相關postgreSql分組數據內容請搜索腳本之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持腳本之家!
您可能感興趣的文章:- postgresql 計算兩點距離的2種方法小結
- postgresql 計算距離的實例(單位直接生成米)
- postgresql 除法保留小數位的實例
- PostgreSQL 性能優化之服務器參數配置操作
- Postgresql的select優化操作(快了200倍)
- Postgresql 動態統計某一列的某一值出現的次數實例