当前位置:网站首页>Clickhouse fields are grouped and aggregated, and SQL is queried according to the granularity of any time period

Clickhouse fields are grouped and aggregated, and SQL is queried according to the granularity of any time period

2022-07-07 01:26:00 Persistence is an attitude

ClickHouse Field grouping aggregation 、 Query according to the granularity of any time period SQL


 Insert picture description here

demand

  • Basic data warehousing , You need to do some aggregation according to the fields
  • Existing intersection passing data , There are various models , It is necessary to count the total flow and the flow of each model , To return together
  • Existing passing data , It needs different granularity according to time , Count the traffic flow , Achieve different time granularity summation ,5 minute 、10 minute 、 Half an hour 、 A month 、 A year will do

solve

Use if and sum

  • Mainly used if, The eligible conditions are 1, The nonconformity is 0, Reuse sum Sum up
select
	count(1) as " Total discharge ",
	SUM(if(vehicle_type = 'PEDESTRIAN', 1, 0)) as " Pedestrian flow ",
	SUM(if(vehicle_type = 'NON_MOTORIZED', 1, 0)) as " Non motor vehicle flow ",
	SUM(if(vehicle_type = 'LIGHT_DUTY', 1, 0)) as " Small traffic flow ",
	SUM(if(vehicle_type = 'MEDIAN_SIZED', 1, 0)) as " Medium traffic flow ",
	SUM(if(vehicle_type = 'OVERSIZE', 1, 0)) as " Large traffic flow "
from
	passing_vehicle
where
	exist_time > 0
	and time_stamp > toDateTime('2022-06-30 11:00:00')
	and time_stamp < toDateTime('2022-06-30 15:00:00')
;

Use toStartOfInterval

select
	toStartOfInterval(time_stamp , INTERVAL 30 minute) as half_hour,
	count(1) as " Total discharge ",
	SUM(if(vehicle_type = 'PEDESTRIAN', 1, 0)) as " Pedestrian flow ",
	SUM(if(vehicle_type = 'NON_MOTORIZED', 1, 0)) as " Non motor vehicle flow ",
	SUM(if(vehicle_type = 'LIGHT_DUTY', 1, 0)) as " Small traffic flow ",
	SUM(if(vehicle_type = 'MEDIAN_SIZED', 1, 0)) as " Medium traffic flow ",
	SUM(if(vehicle_type = 'OVERSIZE', 1, 0)) as " Large traffic flow "
from
	passing_vehicle
where
	exist_time > 0
	and time_stamp > toDateTime('2022-06-30 11:00:00')
	and time_stamp < toDateTime('2022-06-30 15:00:00')
group by
	half_hour,
order by
	half_hour;
原网站

版权声明
本文为[Persistence is an attitude]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/188/202207061732061045.html