BigQuery如何用窗口函数按factory_id获取首末读取日期及总计数
BigQuery 工厂传感器采集日期范围统计实现
当前对接的是传感器采集明细表,用户提供了样例输出参考,表内除factory_id、read_date等核心字段外还包含更多业务字段,需要实现的统计需求为:
- 按
factory_id维度,统计每个工厂对应的最早采集日期first_read_date、最晚采集日期last_read_date - 同步输出全表总记录数
total_count - 运行环境为BigQuery
之前尝试用窗口函数实现需求时,出现last_read_date统计结果不正确的问题,编写的参考SQL如下:
with temptable as( select factory_id, read_date, rank() over(partition by factory_id order by read_date asc) as Ranked_first_read_date, rank() over(partition by factory_id order by read_date desc) as Ranked_last_read_data, concat(read_date,' _ ',rank() over(partition by factory_id order by read_date asc)) as first_read_date , concat(read_date,' _ ',rank() over(partition by factory_id order by read_date desc)) as last_read_date, count(*) over() as total_count from TestDatabase.sensor_data order by factory_id,read_date) select * from temptable a where Ranked_first_read_date=1 and Ranked_last_read_data=(select max(b.Ranked_last_read_data) from temptable b where a.factory_id=b.factory_id group by factory_id)
原有代码的核心问题
- 筛选逻辑存在根本冲突:WHERE条件要求单条记录同时满足「是工厂最早采集记录(升序排名第1)」和「是工厂最晚采集记录(降序排名为组内最大值)」,除工厂仅存1条采集记录的极端场景外,两类记录分属不同行,根本无法同时命中条件,最终导致
last_read_date结果完全不正确 - 冗余逻辑:将日期和排名值拼接成字符串作为字段值,无实际业务意义
- 性能损耗:多层CTE嵌套+关联子查询计算最大排名值,会额外增加全表扫描次数,拉高查询耗时
正确实现方案
两种BigQuery兼容的高效写法,可根据后续扩展需求选择:
写法1:聚合函数直接统计(性能最优)
SELECT factory_id, MIN(read_date) AS first_read_date, MAX(read_date) AS last_read_date, COUNT(*) OVER () AS total_count FROM TestDatabase.sensor_data GROUP BY factory_id
逻辑说明:
- 按
factory_id分组后,直接用MIN()取组内最早采集日期、MAX()取组内最晚采集日期,完全匹配按工厂维度统计的要求 - 用无分区的窗口函数
COUNT(*) OVER ()直接获取全表总记录数,不需要额外触发全表扫描计算
写法2:窗口函数直取聚合值(适合后续扩展复杂逻辑)
如果后续需要保留原始表的其他字段做关联分析,可使用无排名筛选的窗口写法:
SELECT DISTINCT factory_id, MIN(read_date) OVER (PARTITION BY factory_id) AS first_read_date, MAX(read_date) OVER (PARTITION BY factory_id) AS last_read_date, COUNT(*) OVER () AS total_count FROM TestDatabase.sensor_data
逻辑说明:
- 对每一行数据按
factory_id分区,附加同组的最早、最晚采集日期值,不需要对行做升序/降序的排名筛选 - 最后用
DISTINCT对重复的factory_id维度值去重,每个工厂仅保留一行统计结果,从根源上避免了行匹配冲突的问题
内容的提问来源于stack exchange,提问作者lili
相关产品推荐
相关产品推荐

