Skip to content

Instantly share code, notes, and snippets.

@Bennyelg
Forked from shotahorii/20171104_2.md
Created February 7, 2019 07:49
Show Gist options
  • Save Bennyelg/8ca21b25395e78efd949e69a84af0746 to your computer and use it in GitHub Desktop.
Save Bennyelg/8ca21b25395e78efd949e69a84af0746 to your computer and use it in GitHub Desktop.
(un)pivot on Presto

Pivot

Query
SELECT
  uid,
  kv['c1'] AS c1,
  kv['c2'] AS c2,
  kv['c3'] AS c3
FROM (
  SELECT uid, map_agg(key, value) kv
  FROM vtable
  GROUP BY uid
) t
Result
uid  c1  c2  c3
---  --  --  --
101  11  12  13
102  21  22  23

Unpivot

Query
SELECT t1.uid, t2.key, t2.value
FROM htable t1
CROSS JOIN unnest (
  array['c1', 'c2', 'c3'],
  array[c1, c2, c3]
) t2 (key, value)
Result
uid  key  value
---  ---  -----
101   c1     11
101   c2     12
101   c3     13
102   c1     21
102   c2     22
102   c3     23
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment