Select record with max value from each group with Query DSL

元气小坏坏 提交于 2020-01-06 01:11:20

问题


I have a score table where I have players scores, and I want select unique records for each player with the biggest score.

Here is the table:

id | player_id | score | ...
1  | 1         |  10   | ...
2  | 2         |  21   | ...
3  | 3         |  9    | ...
4  | 1         |  30   | ...
5  | 3         |  2    | ...

Expected result:

id | player_id | score | ...
2  | 2         |  21   | ...
3  | 3         |  9    | ...
4  | 1         |  30   | ...

I can achieve that with pure SQL like this:

SELECT *
FROM player_score ps
WHERE ps.score = 
(
    SELECT max(ps2.score)
    FROM player_score ps2
    WHERE ps2.player_id = ps.player_id
) 

Can you tell me how to achieve the same query with query dsl? I found some solutions with JPASubQuery but this class doesn't work for me (my IDE cannot resolve this class). I am using querydsl 4.x. Thank you in advance.


回答1:


JPASubQuery has been removed in querydsl 4. Instead use JPAExpressions.select. Your WHERE clause should look something like this:

.where(playerScore.score.eq(JPAExpressions.select(playerScore2.score.max())
                            .from(playerScore2))
                            .where(playerScore2.playerId.eq(playerScore.playerId)))


来源:https://stackoverflow.com/questions/53226053/select-record-with-max-value-from-each-group-with-query-dsl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!