Last active
December 10, 2021 08:01
-
-
Save channainfo/35ae69b479336b2e0a34808e4dcc72b8 to your computer and use it in GitHub Desktop.
Nested set with full ancestors path for pandas data wragling
This file contains hidden or 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
WITH | |
ancesstor_taxons AS ( | |
SELECT | |
taxon.id as taxon_id, | |
taxon.taxon_type as taxon_type, | |
taxon.parent_id, | |
ancesstor.id AS ancesstor_id, | |
ancesstor.parent_id AS ancesstor_parent_id, | |
trans.name AS ancesstor_name, | |
taxon.lft, | |
taxon.rgt, | |
taxon.depth | |
FROM | |
spree_taxons AS taxon, | |
spree_taxons AS ancesstor | |
INNER JOIN spree_taxon_translations AS trans ON trans.spree_taxon_id = ancesstor.id | |
WHERE | |
trans.locale = 'en' | |
AND ancesstor.lft <= taxon.lft | |
AND ancesstor.rgt >= taxon.rgt | |
AND ancesstor.parent_id IS NOT NULL | |
ORDER BY ancesstor.lft | |
), | |
taxon_with_list_ancesstor AS ( | |
SElECT | |
taxon_id, | |
taxon_type, | |
STRING_AGG(ancesstor_id::varchar, ' -> ' ORDER BY ancesstor_id ASC ) AS ancesstor_ids, | |
STRING_AGG(ancesstor_name::varchar, ' -> ' ORDER BY ancesstor_id ASC ) AS ancesstor_names | |
FROM ancesstor_taxons | |
GROUP BY taxon_id, taxon_type | |
) | |
-- SElECT * FROM ancesstor_taxons; | |
SELECT * FROM taxon_with_list_ancesstor; |
Author
channainfo
commented
Dec 10, 2021
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment