SPB Git

Repository Public

07c_postcode.sql 2.0 KB 40 lines sql

1-- =============================================================================2-- SP BOUCHER | SOURCE FILE3-- =============================================================================4-- Project      : KA Maps Engine5-- File         : server/pipeline/geo/07c_postcode.sql6-- Author       : Simon-Pierre Boucher | https://spboucher.ai7-- Contact      : support@spboucher.ai8-- Copyright    : (c) 2026 Simon-Pierre Boucher9-- License      : None specified (no license file in this repository)10-- =============================================================================11-- END OF SP BOUCHER SOURCE HEADER12-- =============================================================================1314SET client_min_messages = warning;15SET work_mem = '512MB';16-- Codes postaux : ISQ « CP Territoires » (point de l'ensemble d'unités le plus peuplé du code), complété par le RNA17DROP TABLE IF EXISTS postcode CASCADE;18CREATE TABLE postcode (19  code   text PRIMARY KEY,20  pt     geometry(Point, 3857) NOT NULL,21  mun_id int,22  n      int NOT NULL DEFAULT 0,23  src    text NOT NULL24);25INSERT INTO postcode (code, pt, mun_id, n, src)26SELECT DISTINCT ON (cp) cp, ST_Transform(ST_SetSRID(ST_MakePoint("long"::float8, lat::float8), 4326), 3857),27       CASE WHEN co_mun ~ '^\d{5}$' AND EXISTS (SELECT 1 FROM mun WHERE id = co_mun::int) THEN co_mun::int END,28       coalesce(nullif(nb_unite_cp, '')::numeric::int, 0), 'isq_cp'29FROM raw_cp30WHERE cp ~ '^[A-Z]\d[A-Z]\d[A-Z]\d$' AND lat ~ '^-?\d' AND "long" ~ '^-?\d' AND nullif(ret_date, '') IS NULL31ORDER BY cp, coalesce(nullif(nb_unite_ad, '')::numeric, 0) DESC;32INSERT INTO postcode (code, pt, mun_id, n, src)33SELECT a.postcode, ST_ClosestPoint(ST_Collect(a.pt), ST_Centroid(ST_Collect(a.pt))), min(s.mun_id), count(*), 'nar'34FROM address a JOIN street s ON s.id = a.street_id35WHERE a.postcode IS NOT NULL GROUP BY a.postcode36ON CONFLICT (code) DO NOTHING;37CREATE INDEX postcode_prefix ON postcode (code text_pattern_ops);38ANALYZE postcode;39SELECT src, count(*) FROM postcode GROUP BY 1;40
Files main
Menu

Theme