当前位置:网站首页>hql求一个范围内最大值
hql求一个范围内最大值
2022-04-23 06:15:00 【山顶看数据】
主要明白的是
字符串是可以进行排序的,但是不能进行最极致,比如这里的日期
这道题就是求在开始时间和结束时间里面的最大的数值,而且还是把两列变成一例的方法
最终查询的答案
select user_id,
max(num) max_num
from (
select id,
user_id,
dt,
sum(p) over(partition by user_id order by dt) num
from (
select id,
user_id,
begin_date dt,
1 p
from test
union
select id,
user_id,
end_date dt,
-1 p
from test
) t1
) t2
group by user_id;
测试语句
create table if not exists test(
id int,
user_id string,
begin_date string,
end_date string
)
row format delimited
fields terminated by ',';
insert into test values(1,'A','2020-01-01','2020-01-30');
insert into test values(2,'A','2020-01-02','2020-01-30');
insert into test values(3,'A','2020-01-10','2020-02-10');
insert into test values(4,'B','2020-02-11','2020-02-30');
insert into test values(5,'C','2020-01-01','2020-01-30');
这里面我们是吧这一张表进行分解,然后再进行合并,获取我们想要的字段
-- 获取开始时间的哪一张表
select id,user_id,begin_date dt, 1 p
from test
1 A 2020-01-01 1
2 A 2020-01-02 1
3 A 2020-01-10 1
4 B 2020-02-11 1
5 C 2020-01-01 1
-- 获取结束时间的哪一张表
select id,user_id,end_date dt, -1 p
from test
1 A 2020-01-30 -1
2 A 2020-01-30 -1
3 A 2020-02-10 -1
4 B 2020-02-30 -1
5 C 2020-01-30 -1
把两张表进行合并(union)(这也是把两列变成一列)
id user_id dt p
1 A 2020-01-01 1
1 A 2020-01-30 -1
2 A 2020-01-02 1
2 A 2020-01-30 -1
3 A 2020-01-10 1
3 A 2020-02-10 -1
4 B 2020-02-11 1
4 B 2020-02-30 -1
5 C 2020-01-01 1
5 C 2020-01-30 -1
然后最这张表进行分组。然后再对dt进行排序,并对p进行求和
1 A 2020-01-01 1
2 A 2020-01-02 2
3 A 2020-01-10 3
2 A 2020-01-30 1
1 A 2020-01-30 1
3 A 2020-02-10 0
4 B 2020-02-11 1
4 B 2020-02-30 0
5 C 2020-01-01 1
5 C 2020-01-30 0
最后就是进行use_id进行分组,去最大的p即可
这个结果就是在一定范围内的最大值,也就是最大的持仓笔数
版权声明
本文为[山顶看数据]所创,转载请带上原文链接,感谢
https://blog.csdn.net/li1579026891/article/details/121764846
边栏推荐
猜你喜欢
excel实战应用案例100讲(八)-Excel的报表连接功能
F. The wonderful use of pad
Gephi tutorial [1] installation
网络层重要知识(面试、复试、期末)
带低压报警的51单片机太阳能充电宝设计与制作(完整代码资料)
Int8 quantification and inference of onnx model using TRT
GIS实战应用案例100篇(五十一)-ArcGIS中根据指定的范围计算nc文件逐时次空间平均值的方法
Wechat applet uses wxml2canvas plug-in to generate some problem records of pictures
AUTOSAR从入门到精通100讲(五十一)-AUTOSAR网络管理
GIS实战应用案例100篇(五十二)-ArcGIS中用栅格裁剪栅格,如何保持行列数量一致并且对齐?
随机推荐
x86架构初探之8086
scons 搭建嵌入式arm编译
画 ArcFace 中的 margin 曲线
armv8m(cortex m33) MPU实战
Device Tree 详解
F. The wonderful use of pad
AUTOSAR从入门到精通100讲(五十)-AUTOSAR 内存管理系列- ECU 抽象层和 MCAL 层
PyTorch 18. torch.backends.cudnn
Int8 quantification and inference of onnx model using TRT
PyTorch 9. optimizer
Gather, unsqueeze and other operators when PTH is converted to onnx
Chapter 3 pytoch neural network toolbox
By onnx checker. check_ Common errors detected by model
pth 转 onnx 时出现的 gather、unsqueeze 等算子
【无标题】制作一个0-99的计数器,P1.7接按键,P2接数码管段,共阳极数码管,P3.0,P3.1接数码管位码,每按一次键,数码管显示加一。请写出单片机的C51代码
Pep517 error during pycuda installation
Wechat applet uses wxml2canvas plug-in to generate some problem records of pictures
字节跳动2020秋招编程题:根据工号快速找到自己的排名
enforce fail at inline_container.cc:222
在项目中的定时作用