JPA DISTINCT和限制结果编号

时间:2016-10-13 08:18:42

标签: sql jpa

我有一张表:

 Id crit1 crit2 value
 1  1     2     a
 2  2     2     b
 3  1     3     c
 4  1     1     d
 5  2     2     e
 6  1     2     f

对于crit1和crit2的每个组合,我想要具有最高Id的值。所以期望的结果是:

 crit1 crit2 value
 1     1     d
 1     2     f
 1     3     c
 2     2     e

如何在JPA中定义查询。 (我试过DISTINCT,它会给出所有6个数据集。如果试图限制它,我只得到1(不是4))。

谢谢!

2 个答案:

答案 0 :(得分:1)

试试这个......

            select crit1 ,crit2, value from 
            ( 
                select   crit1 ,crit2, value, ROW_NUMBER() OVER ( PARTITION  BY crit1 , crit2 
                ORDER BY id desc ) as rank from #table_name t
            )a where a.rank=1

答案 1 :(得分:0)

您可以按crit1crit2创建子查询分组,并获取每个组的最大ID:

select max(e.id) from MyEntity e group by e.crit1, e.crit2

然后,您可以创建一个查询,仅显示子查询中ID所需的数据过滤:

select e.crit1, e.crit2, e.value 
from MyEntity e 
where e.id in (select max(sub.id) from MyEntity sub group by sub.crit1, sub.crit2)
order by e.crit1, e.crit2