Last active
November 1, 2022 17:18
-
-
Save ip75/a8467a3476ee7c84840bccbaafaaba20 to your computer and use it in GitHub Desktop.
example of recursive select in postgres
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
--- in database of ФИАС get address records recursively until root record | |
WITH RECURSIVE parent AS | |
( SELECT a.* | |
FROM addrobj a | |
WHERE a.aoguid = @locality | |
AND a.actstatus = 1 | |
UNION ALL | |
SELECT ao.* | |
FROM parent p | |
JOIN addrobj ao ON p.parentguid = ao.aoguid | |
WHERE p.aoguid IS NOT NULL | |
AND ao.actstatus = 1) | |
SELECT * | |
FROM parent |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
--- group by update date and get latest set of addresses | |
WITH addrobj_noduplicates AS " + | |
( | |
SELECT *, ROW_NUMBER() OVER (PARTITION BY fa.aoguid ORDER BY fa.startdate DESC) as rn | |
FROM fias.addrobj fa | |
WHERE | |
fa.aolevel = ANY (:aolevel) | |
AND fa.actstatus=1 | |
AND fa.formalname ~* @region | |
ORDER BY fa.aolevel, fa.startdate DESC | |
LIMIT @limit | |
) | |
SELECT * | |
FROM addrobj_noduplicates fa | |
WHERE | |
fa.rn = 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment