title: Distinct sum in Hibernate using multiple joins
body: <p>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.</p>
  
  <p>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?</p>
  
  <pre><code>@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) &gt; b.maxCount")
  </code></pre>
  
  <p>Relations between tables:</p>
  
  <ul>
  <li>many usergroups to many nusers.</li>
  <li>many directorys to one nuser.</li>
  <li>many files to one directory.</li>
  <li>many histories to one nuser.</li>
  </ul>