postgres數據庫中獲取當前日期、周幾,還有列轉行和hive中獲取當前日期、string轉成map、列轉行的代碼

--postgresSQL寫法 需求都是同一roadid下,求每15分鐘的均速km/h

 create table if not exists avg_speed_week_day0 as (
 		select c.roadid,c.week_day,
	
		max(case when cast(btrim(c.times,'h')as int)  = 000  then c.avg_speed else 0  end ) as "h0000", -- 00
		max(case when cast(btrim(c.times,'h')as int)  = 015  then c.avg_speed else 0  end ) as "h0015",
		max(case when cast(btrim(c.times,'h')as int)  = 030  then c.avg_speed else 0  end ) as "h0030",
		max(case when cast(btrim(c.times,'h')as int)  = 045  then c.avg_speed else 0  end ) as "h0045"
        	from 
				(select b.roadid,b.week_day,b.times, 
						round((sum(b.speed)/count(*)) * 3.6) as avg_speed
				from

						(select a.roadid,a.speed,a.week_day,a.utc,
								case when minute=0 
									then concat('h',hour,'00')
									else concat('h',hour,minute*15)
								end times
						from
								(select roadid,speed,utc,
										EXTRACT(DOW FROM TO_TIMESTAMP(utc)) week_day,  --周幾 週一顯示 1,週日顯示0,週六顯示6
										extract(hour from TO_TIMESTAMP(utc)) as hour,   --小時 比如凌晨1點 取出只是1,早上10點取出是10
										floor(cast(extract(minute from to_timestamp(utc))as int)/15)  as minute --分鐘
								from bj_speed_0219 
								--where roadid='20000015607528'
								) as a 
						) as b
				group by b.roadid,b.week_day,b.times
				) as c
		group by c.roadid,c.week_day
		having week_day = 0
		);
 
--hiveSQL寫法

select d.roidid,d.week_day,
       d.tags['h0000'] h0000,d.tags['h0015'] h0015,d.tags['h0030'] h0030,d.tags['h0045'] h0045,
       d.tags['h0100'] h0100,d.tags['h0115'] h0115,d.tags['h0030'] h0030,d.tags['h0145'] h0145,
       ...
       d.tags['h2300'] h2300,d.tags['h2315'] h2315,d.tags['h2330'] h2330,d.tags['h2345'] h2345,
	   
from	   
	(select c.roidid,c.week_day,STR_TO_MAP(CONCAT_WS(',',COLLECT_SET(CONCAT(c.time,':',c.avg_speed)))) AS tags
	from
			(select b.roidid,b.week_day,b.time,sum(b.speed)/count(*) avg_speed
			from
					(select a.roidid,a.speed,a.week_day,
						case when minute=0 then concat('h',hour,'00')
							else concat('h',hour,sort*15)
						end time
					from
							(select roidid,speed,
									pmod(datediff(FROM_UNIXTIME(utc,'yyyy-MM-dd'), '2012-01-01'), 7) week_day, --周幾
									hour(from_unixtime(utc,'yyyyMMdd HH:mm:ss')) as hour, --小時
									floor(cast(minute(from_unixtime(utc)) as int)/15 ) as minute --分鐘
							from table
							)a
					) b
			group by b.roidid,b.week_day,b.time
			) c
	group by c.roidid,c.week_day
	) d
;

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章