我有以下结构。不是在一个表中,只是为了保持简单:
Press | Batch | Start time
-------------------------------------------------
PRESS_1 | 2051 | 2017-05-18T00:00:00
PRESS_1 | 2052 | 2017-05-19T00:00:00
PRESS_2 | 2053 | 2017-05-20T00:00:00
PRESS_2 | 2054 | 2017-05-16T00:00:00
PRESS_3 | 2055 | 2017-05-12T00:00:00
PRESS_3 | 2056 | 2017-05-18T00:00:00
PRESS_3 | 2057 | 2017-05-19T00:00:00
我想获得每个印刷机的最后计划批次。结果应该是:
Press | Batch | Start time
-------------------------------------------------
PRESS_1 | 2052 | 2017-05-19T00:00:00
PRESS_2 | 2053 | 2017-05-20T00:00:00
PRESS_3 | 2057 | 2017-05-19T00:00:00
然而,当我按下分组并且还想选择批次时。我有义务将这批产品放入' Group By'条款。
Select x.Press, x.Batch, max(x.StartTime)
From myTable x
Group by x.Press
如何使用JPQL实现这一目标?
答案 0 :(得分:2)
如果您想选择每次按下最大start_time的条目,您也可以使用下面提到的内容 -
Select x.Press, x.Batch, x.StartTime
From x
where (press,starttime) in
(select press, max(starttime)
from x group by press)
试试看,请告诉我。
答案 1 :(得分:1)
您可以使用带有聚合结果的内部联接进行分组
select * from my_table as t1
inner join (
select Press, max(start_time) my_time
from my_table
group by Press ) t2 on t1.Press = T2.Press and t2.my_time = t1.start_time
或避免加入
select * from my_table as t1
where (t1.Press, t1.start_time) in (
select Press, max(start_time)
from my_table
group by Press )
如果您的ORM有限,您可以创建一个正确的视图,然后使用视图名称作为避免子查询的表
答案 2 :(得分:0)
您应该能够从批处理中获得最大值,假设您在每个开始时间批量增加:
Select x.Press, max(x.Batch), max(x.StartTime)
From x
Group by x.Press