title: Postgresql query with double has_many relationships
body: <p>I have this complex data relationship.</p>
  <p>POSTGRESQL FIDDLE: <a href="https://www.db-fiddle.com/f/vm2z8qLuddzcHEgyaMnCbc/3" rel="nofollow noreferrer">https://www.db-fiddle.com/f/vm2z8qLuddzcHEgyaMnCbc/3</a></p>
  <p>&quot;Item Group&quot; has many &quot;items&quot; through &quot;item_ads&quot; table.
  So an Item Group has many part_number.</p>
  <p><a href="https://i.stack.imgur.com/tLAve.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tLAve.png" alt="enter image description here" /></a></p>
  <p>reports table contains the number of clicks for each day for each adgroupid.</p>
  <p>Each <em>adgroupid</em> has_many <em>part_numbers</em>. (table: product_ads)</p>
  <p><a href="https://i.stack.imgur.com/bWncl.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bWncl.png" alt="enter image description here" /></a></p>
  <p>Now, I want to SUM all reports.clicks for each item_groups.id using the part_number to linked the tables.</p>
  <p>After this, I have to consider only reports.adgroupid which are included in the part_numbers of item_group. So if &quot;Item group&quot; has three part_number (A, B, C) can be considered all adgroupid that contains A,B, or C but nothing more. If adgroupid contains part_number D it cannot be considered for clicks sum.</p>
  <p><strong>Expected results</strong></p>
  <p><a href="https://i.stack.imgur.com/4Yvw0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4Yvw0.png" alt="enter image description here" /></a></p>
  <p>I have to have a table with lots of item_group_ids.
  I am looking for the PostgreSQL query to achieve this table.</p>