hql面试题之上海某资深数仓开发工程师面试题-求不连续月份的月平均值

1.题目

A,B两组产品的月平均值,月平均值是当月的前三个月值的一个平均值,注意月份是不连续的,如果当月的前面的月份不存在,则为0。如A组2023-04的月平均值为2023年1月的数据加2023-02月的数据的平均值,因为没有其他月份则需要再加一个0,再求平均值。要求:求出每个月的月平均值。

'A','2023-01',3030

'A','2023-02',5464

'A','2023-04',5467

'A','2023-05',4646

'A','2023-06',8546

'B','2022-01',9846

'B','2022-02',1562

'B','2022-03',2733

'B','2022-05',8833

'B','2022-06',8787

2.建表

sql 复制代码
create table if not exists non_continuous_time(
product string comment '产品号',
pro_time string comment '时间',
pro_values int comment '值'
)comment '非连续时间表'
sql 复制代码
insert into non_continuous_time values
('A','2023-01',3030),
('A','2023-02',5464),
('A','2023-04',5467),
('A','2023-05',4646),
('A','2023-06',8546),
('B','2022-01',9846),
('B','2022-02',1562),
('B','2022-03',2733),
('B','2022-05',8833),
('B','2022-06',8787)

3.思路

使用lag窗口函数,lag的偏移量可以锁定前三个月的数据,没有的显示为0;

sql 复制代码
select 
   product,
   pro_time,
   pro_values,
   coalesce(lag(pro_values,1) over(partition by product order by pro_time),0) lg_one,
   coalesce(lag(pro_values,2) over(partition by product ORDER BY pro_time),0) lg_two,
   coalesce(lag(pro_values,3) over(partition by product ORDER BY pro_time),0) lg_thr
from non_continuous_time

最终结果:

sql 复制代码
select
    a.product,
    a.pro_time,
   (lg_one+lg_two+lg_thr)/3  sum_values
from
(
select 
   product,
   pro_time,
   pro_values,
   coalesce(lag(pro_values,1) over(partition by product order by pro_time),0) lg_one,
   coalesce(lag(pro_values,2) over(partition by product ORDER BY pro_time),0) lg_two,
   coalesce(lag(pro_values,3) over(partition by product ORDER BY pro_time),0) lg_thr
from non_continuous_time
)a
相关推荐
codeejun8 小时前
每日一Go·MySQL-15、慢查询日志实战分析(从 0 到 1 实战排查慢 SQL)
sql·mysql·golang
Decay__10 小时前
SQLServer 监控体系构建 —— sql_exporter + Prometheus + Grafana 全栈实战
运维·数据库·sql·mysql·架构
Pniubi2 天前
怎么排查慢SQL,怎么解决?
java·数据库·sql
Decay__2 天前
VMware 安装 SQL Server 双节点 AlwaysOn 可用性组教程 —— WSFC、AG 与侦听器完整部署(系列核心篇)
运维·数据库·sql·mysql·架构
茶栀(*´I`*)2 天前
SQL 性能分析:从慢查询日志到执行计划的完整定位方法
数据库·sql
乌暮2 天前
Spring AOP 与 Spring 事务:用大白话彻底理解原理与实践
java·数据库·spring boot·后端·sql·学习·spring
吾AI科技3 天前
基于Tez引擎的 Hive SQL 性能优化 —— 为什么脚本运行越来越慢
大数据·hive·性能优化·tez
AllData公司负责人3 天前
AI大模型数据开发底座系列说明书,AllData集成Chat2DB开源项目建设AI 数据库分析底座,涵盖AI 洞察/对话SQL/智能视图!
数据库·人工智能·sql·开源·ai 洞察·对话sql
Decay__3 天前
SQLServer 索引与 SQL 优化 —— 聚集索引、非聚集索引、覆盖索引、碎片维护与执行计划
运维·数据库·sql·mysql·架构
星恒随风4 天前
MySQL 从零入门(五):MySQL 内置函数详解——日期、字符串、数学函数与实战案例
linux·数据库·笔记·sql·mysql