Skip to content

Instantly share code, notes, and snippets.

@lissahyacinth
Last active May 16, 2017 22:45
Show Gist options
  • Save lissahyacinth/d02c9943cafc6541a7f85d665b99d360 to your computer and use it in GitHub Desktop.
Save lissahyacinth/d02c9943cafc6541a7f85d665b99d360 to your computer and use it in GitHub Desktop.
Presto SQL Generic Structure for sorting an array by another array
-- LINES 1 - 4: Transform( to x -> ELEMENT_AT
-- The TRANSFORM orders the array by a transform of the array.
-- Channel Array is of form A#T :: String, where T :: Integral
-- RESULT: An ordered array :: Integral, which will form our keys for the second section.
-- LINES 5 - 11: ELEMENT_AT( to END
-- We now take our keys one by one, and use them in ELEMENT_AT(mapping, key) to generate a new array.
-- As our keys are in the right order, our end array will also be. (Duplicate keys will cause a missing hit.)
-- The other lines generate the actual map.
-- RESULT: An ordered array.
WITH
ARRAY_SORT_BY AS (
SELECT
TRANSFORM(
ARRAY_SORT(
TRANSFORM(ARRAY_A, x -> CAST(REGEXP_EXTRACT(x, '#(.*)', 1) AS BIGINT))
),
x -> ELEMENT_AT(
MAP(
TRANSFORM(ARRAY_A, x -> CAST(REGEXP_EXTRACT(x, '#(.*)', 1) AS BIGINT)),
ARRAY_A
),
x)
)
)
SELECT * FROM ARRAY_SORT_BY
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment