您好,登錄后才能下訂單哦!
怎么在postgreSql數(shù)據(jù)庫中實現(xiàn)分組統(tǒng)計數(shù)據(jù)?很多新手對此不是很清楚,為了幫助大家解決這個難題,下面小編將為大家詳細(xì)講解,有這方面需求的人可以來學(xué)習(xí)下,希望你能有所收獲。
比如氣象臺的氣溫監(jiān)控,每半小時上報一條數(shù)據(jù),有很多個地方的氣溫監(jiān)控,這樣數(shù)據(jù)表里就會有很多地方的不同時間的氣溫數(shù)據(jù)
每次查詢只查最新的氣溫數(shù)據(jù)按照不同的溫度區(qū)間來分組查出,比如:高溫有多少地方,正常有多少地方,低溫有多少地方
3.1 創(chuàng)建表結(jié)構(gòu):
-- 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 造數(shù)據(jù)
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.1 需求1的SQL語句
利用了postgreSql的一個函數(shù):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
效果如下,查出的都是最新的數(shù)據(jù):
4.2 需求2的SQL語句
利用了一個case when then else end 用法來統(tǒng)計數(shù)量
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
效果如下,因為沒有過濾每個地方的最新數(shù)據(jù),查出的是所有數(shù)據(jù):
用需求1的結(jié)果來查詢統(tǒng)計:
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統(tǒng)計,就能查出低溫天氣,正常天氣,高溫天氣分別合計數(shù)量是多少了。
看完上述內(nèi)容是否對您有幫助呢?如果還想對相關(guān)知識有進(jìn)一步的了解或閱讀更多相關(guān)文章,請關(guān)注億速云行業(yè)資訊頻道,感謝您對億速云的支持。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。