Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
898 views
in Technique[技术] by (71.8m points)

Sum a List of averages in spring boot jpa query

I have this query thats return a list of averages

@Query("SELECT AVG(p.quantity) FROM Position p GROUP BY p.client.id") public List<Float> findAVGPositions();

But I want to return SUM of averages like this, but it doesn't work

@Query("SELECT SUM(averages) FROM (SELECT AVG(p.quantity) as averages FROM Position p GROUP BY p.client.id)") public Float findSumAVGPositions();

Can you help me? thanks

question from:https://stackoverflow.com/questions/65617511/sum-a-list-of-averages-in-spring-boot-jpa-query

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Unfortunately, in JPQL, nested selects are not permitted in FROM clause. They are allowed only in SELECT and WHERE.

You have two approaches available.

(1) Use findAVGPositions and calculate sum in Java

    findAVGPositions().stream().reduce(0f, Float::sum);

(2) Use a native SQL query

    @Query(value = "SELECT SUM(averages) " +
                   "FROM (SELECT AVG(p.quantity) AS averages " +
                         "FROM position p " +
                         "GROUP BY client_id) AS averages_select",
            nativeQuery = true)
    public Float findSumAVGPositions();

Depending on the database you use, AS averages_select alias might be needed or not (PostgreSQL requires it, even if it's not used).

Please, pay attention to use the correct names of a database table for Position entity and a database column for a foreign key client.id.

In my example, I assumed a standard mapping convention: position as a table name, and client_id as a foreign key column.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...