title: Remove repeated SPARQL sub-query to compare against the average
body: <p>Here is a subquery that counts the number of subject for 10 values of the object from the triples of the form <code>?sbj pq:P1810 ?obj</code> . The predicate <code>pq:P1810</code> is used because it is available from wikidata, we could use <code>?person foaf:name ?name</code> instead, but FOAF is not available in wikidata.</p>
  <pre><code>SELECT ?obj (COUNT(?sbj) AS ?num_sbj) WHERE {
      ?sbj pq:P1810 ?obj .
  } GROUP BY ?obj LIMIT 10
  </code></pre>
  <p>I would like to select all <code>?obj</code>, which have a higher <code>?num_sbj</code> than the average. The working solution I came up  with is this :</p>
  <pre><code>SELECT ?obj ?num_sbj ?avg_num_sbj WHERE {
      {
          SELECT ?obj (COUNT(?sbj) AS ?num_sbj) WHERE {
              ?sbj pq:P1810 ?obj .
          } GROUP BY ?obj LIMIT 10
      }
      {
          SELECT (AVG(?num_sbj_) AS ?avg_num_sbj) WHERE {
              {
                  SELECT ?obj_ (COUNT(?sbj_) AS ?num_sbj_) WHERE {
                      ?sjb_ pq:P1810 ?obj_ .
                  } GROUP BY ?obj_ LIMIT 10
              }
          }
      }
      FILTER (?num_sbj &gt; ?avg_num_sbj)
  }
  </code></pre>
  <p>Here is a link to a running example in wikidata <a href="https://w.wiki/5Ci7" rel="nofollow noreferrer">https://w.wiki/5Ci7</a></p>
  <p>Unfortunately, the first sub-query has to be repeated in the second sub-query to fetch the average.</p>
  <p>Is the subquery actually performed more than once? I feel like a query optimizer could see that the queries are the same and perform the reduction on a copy of the data, but I'm not sure whether this optimization would always be present.</p>
  <p>Is it possible to reformulate the working solution such that no subquery is written more than once ?</p>