query-063b04be1b98af0a222cc281bf470723

rq turtle/ttl

Oravrattas

Use at

PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
PREFIX wdt: <http://www.wikidata.org/prop/direct/>
PREFIX wd: <http://www.wikidata.org/entity/>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX ps: <http://www.wikidata.org/prop/statement/>
PREFIX pq: <http://www.wikidata.org/prop/qualifier/>
PREFIX p: <http://www.wikidata.org/prop/>
SELECT DISTINCT ?date ?age ?president ?presidentLabel
WHERE
{
  # A result is a change from the previous date if ?president's presidency ended the day before ?date,
  # or if an older expresident died the day before ?date. Filter out results that don't fulfill this.

{
  SELECT DISTINCT ?date ?age ?president ?presidentLabel ?president_birthdate
  WHERE
  {

{
  # Dates where who is oldest living expresident can change
  SELECT DISTINCT ?date
  WHERE
  {
    {
      INCLUDE %presidents
      BIND(?president_enddate + "P1D"^^xsd:duration AS ?date)
    }
    UNION
    {
      INCLUDE %presidents
      BIND(?president_deathdate + "P1D"^^xsd:duration AS ?date)
    }
  }
}    OPTIONAL
    {

{
  # Find the age for all living expresidents for each value of ?date
  SELECT ?date ?age ?president ?presidentLabel ?president_birthdate
  WHERE
  {

{
  # Dates where who is oldest living expresident can change
  SELECT DISTINCT ?date
  WHERE
  {
    {
      INCLUDE %presidents
      BIND(?president_enddate + "P1D"^^xsd:duration AS ?date)
    }
    UNION
    {
      INCLUDE %presidents
      BIND(?president_deathdate + "P1D"^^xsd:duration AS ?date)
    }
  }
}    INCLUDE %presidents
    FILTER (?president_enddate < ?date) # Must have become expresident
    FILTER IF(BOUND(?president_deathdate), ?president_deathdate >= ?date, true) # Must still be living
    BIND (?date - ?president_birthdate AS ?age)
  }
}      
{
  # Find the oldest age for a living expresident for each value of ?date
  SELECT ?date (MAX(?age) AS ?oldest)
  WHERE
  {
    INCLUDE %ages
  }
  GROUP BY ?date
}      FILTER (?age = ?oldest)
    }
  }
}  BIND (?date - "P1D"^^xsd:duration AS ?day_before)
  FILTER
  (
    ! BOUND(?president) ||
    EXISTS
    {
      ?president p:P39 ?president_statement.
      ?president_statement ps:P39 wd:Q11696.
      ?president_statement pq:P582 ?day_before.
    } ||
    EXISTS
    {
      ?other_president wdt:P31 wd:Q5.
      ?other_president p:P39 ?president_statement.
      ?president_statement ps:P39 wd:Q11696.
      ?president_statement pq:P582 ?other_president_end.
      ?other_president wdt:P569 ?other_president_birthdate.
      ?other_president wdt:P570 ?day_before.
      FILTER (?other_president_birthdate < ?president_birthdate) # Other president is oldest
      FILTER (?other_president_end < ?day_before) # other president died as expresident
    }
  )
}
ORDER BY ?date

Query found at