Created
April 22, 2017 18:46
-
-
Save matthew-n/8fdd902c81ac605956fad8415a777be3 to your computer and use it in GitHub Desktop.
postgresql unpivot with hstore example
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
WITH fedex_rates_ip | |
("fid","Type","Weight","ZoneA","ZoneB","ZoneC","ZoneD","ZoneE","ZoneF","ZoneG", | |
"ZoneH","ZoneI","ZoneJ","ZoneK","ZoneL","ZoneM","ZoneN","ZoneO","ZonePuertoRico") | |
as( | |
select | |
* | |
from ( | |
values | |
(2,'IntlPriority',0,40.25,41.5,43,54.75,116.5,52,51.5,61.25,49.5,63.5,62.5,82,119.25,61,63.25,36.65), | |
(3,'IntlPriority',-1,66.25,67.75,62.25,74.25,132,68,68.25,85.75,66.25,84.5,82.25,99.5,136.5,79.75,85.5,null), | |
(4,'IntlPriority',-2,70.25,73.5,65.75,77.25,156.25,73,73.25,87.25,73.5,90.5,87.75,129.25,160.75,86,96,null) | |
) as x | |
) | |
, fkv AS ( | |
SELECT | |
f."Type" As type, | |
f."Weight" As weight, | |
from fedex_rates_ip AS f | |
latteral each(hstore(f) - '{fid,Type,Weight}'::text[]) AS kv | |
) | |
SELECT | |
type, | |
weight, | |
(kv).key AS zone, | |
(kv).value::numeric As price | |
FROM fkv; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The use of hstore to remove multiple keys will be superseded in Postgresql 10 by
operator - (json,text[])
andoperator - (jsonb, text[])
that will removed multiple keys at the current top level.