I am trying to get the sum of the size of files contained in a directory for a group. However, the size is being multiplied due to the number of rows returned from the joins. I also have other tables contained in my query to get history information. I have a PostgreSQL database and I am using a hibernate query in my repository interface.
Online, it says I need to subquery my aggregation. However I need to join all these tables to get the files relating to the directory which relate to the user which relates to the group. How can I do a distinct sum?
@Query(value = "select a.username as name, sum(d.filesize) as size"
+ "from usergroup a "
+ "join a.nuser b "
+ "join b.directory c "
+ "join c.files d "
+ "join b.nuserhistory e"
+ "group by a.name"
+ "having count(e) > b.maxCount")
Relations between tables:
- many usergroups to many nusers.
- many directorys to one nuser.
- many files to one directory.
- many histories to one nuser.