R2D2
R2D2

Reputation: 3

Wikidata SPARQL: How to filter by date if available?

I want a list of all dial codes and postal codes of Germany, but some towns have data for old postal codes and this query returns one of them, but not the newest:

SELECT DISTINCT ?item ?itemLabel ?officialName ?dialcode ?zipCode
WHERE { 
    ?item p:P31/ps:P31/wdt:P279* wd:Q262166;
           wdt:P17 wd:Q183;     # Country = Germany
           wdt:P131 wd:Q10489;  # County
           wdt:P281 ?zipCode; wdt:P473 ?dialcode; .
  SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
    OPTIONAL{?item wdt:P1448 ?officialName .}
}                                               
ORDER BY DESC(?zipCode) ?dialcode

The town of Hautzenberg returns W-8395 as postal code instead of 94051, because this is one of the few towns in the database with start and end date of the postal codes. But most of the postal codes doesn't have any dates. If no date is given it should also deliver the postal code.

This is the data of Hautzenberg: https://www.wikidata.org/wiki/Q255888

Upvotes: 0

Views: 272

Answers (1)

logi-kal
logi-kal

Reputation: 7880

Indeed Hautzenberg returns 4 codes, among which there is also 94051.

If you want only 94051 you have to filter by date.

Heuristically, you can filter out the claims which do have an end time:

SELECT DISTINCT ?item ?itemLabel ?officialName ?dialcode ?zipCode
WHERE { 
    ?item p:P31/ps:P31/wdt:P279* wd:Q262166;
          wdt:P17 wd:Q183;     # Country = Germany
          wdt:P131 wd:Q10489;  # County
          p:P281 ?zipCodeStmt;
          wdt:P473 ?dialcode; .
  ?zipCodeStmt ps:P281 ?zipCode;
  FILTER NOT EXISTS { ?zipCodeStmt pq:P582 ?endTime . } # Filtering out old postal codes
  SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
  OPTIONAL { ?item wdt:P1448 ?officialName . }
}                                               
ORDER BY DESC(?zipCode) ?dialcode

Upvotes: 1

Related Questions