query: select distinct ?item ?list ?count ?count2 with
  { 
    select ?item where
    {
      { ?item wdt:P31 wd:Q18115939 . } union { ?item wdt:P31 wd:Q56760832 } . # ambassador or high commissioner
    } } as %i with 
  { select ?item (count(?person) as ?count) where
    {
      include %i 
      optional {?person wdt:P39 ?item .} 
    } group by ?item  } as %p with 
  { select ?item (count(?thing2) as ?count2) where
    {
      include %i 
      optional {?person wdt:P39 ?item .}
      optional {?person p:P39 [ps:P39 ?item; pq:P580 ?start] .}
      bind(if(!bound(?start),1,?start) as ?thing)
      bind(concat(str(?person),str(?thing)) as ?thing2)
    } group by ?item } as %q where
  {
    include %i
    include %p
    include %q
    BIND (xsd:integer( SUBSTR(STR(?item), 33) ) as ?itemNumber)
    BIND ("https://query.wikidata.org/#select%20%3Fperson%20%3FpersonLabel%20%3Fstartyear%20%3Fendyear%20where%0A%7B%0A%20%20%3Fperson%20p%3AP39%20%3FpositionStatement%20.%20%3FpositionStatement%20ps%3AP39%20wd%3AQXXX%20.%20%0A%20%0A%20%20optional%20%7B%20%3FpositionStatement%20pq%3AP580%20%3Fstart%20.%20bind%28year%28%3Fstart%29%20as%20%3Fstartyear%29%20%7D%20%23%20id%20start%20year%0A%20%20optional%20%7B%20%3FpositionStatement%20pq%3AP582%20%3Fend%20.%20bind%28year%28%3Fend%29%20as%20%3Fendyear%29%20%7D%20%23%20id%20end%20year%0A%20%20SERVICE%20wikibase%3Alabel%20%7B%20bd%3AserviceParam%20wikibase%3Alanguage%20%22%5BAUTO_LANGUAGE%5D%2Cen%22.%20%7D%0A%7D%20order%20by%20%3Fstartyear" as ?query_template)       
    BIND (REPLACE(?query_template,"XXX", STR(?itemNumber)) as ?list_ambs) #generate query URL by inserting QId into template
    BIND (concat("[",str(?list_ambs)," List ambassadors]") as ?list) 
  }