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
相关推荐
SoFlu软件机器人8 小时前
告别手动报表开发!描述数据维度,AI 自动生成 SQL 查询 + Java 导出接口
java·数据库·sql
云边散步12 小时前
🥢 第2篇:SELECT就是点菜,FROM就是菜单 —— 写你人生第一句SQL!
sql·mysql
王小王-12313 小时前
基于Hadoop与LightFM的美妆推荐系统设计与实现
大数据·hive·hadoop·大数据美妆推荐系统·美妆商品用户行为·美妆电商
见未见过的风景1 天前
想删除表中重复数据,只留下一条,sql怎么写
数据库·sql
hello 早上好1 天前
MyBatis 动态 SQL、#{}与 ${}区别、与 Hibernate区别、延迟加载、优势、XML映射关系
sql·mybatis·hibernate
万能小锦鲤1 天前
《大数据技术原理与应用》实验报告七 熟悉 Spark 初级编程实践
hive·hadoop·ubuntu·flink·spark·vmware·实验报告
NullPointerExpection1 天前
LLM大语言模型不适合统计算数,可以让大模型根据数据自己建表、插入数据、编写查询sql统计
数据库·人工智能·sql·算法·llm·llama·工作流
我命由我123451 天前
Spring Boot - Spring Boot 集成 MyBatis 分页实现 手写 SQL 分页
java·spring boot·后端·sql·spring·java-ee·mybatis
切糕师学AI1 天前
SQL中对字符串字段模糊查询(LIKE)的索引命中情况
数据库·sql
茅坑的小石头1 天前
SQL,在join中,on和where的区别
sql