简体   繁体   中英

Transpose non Numeric column in Redshift

I have a data set that looks like the following: Index, Key, Value

1, Description, Apple
2, Type, Orange
3, Desciption, Apple
4, Type, Pickle
5, Type, Orange 

I know this can be done if Value is numeric with this:

select Index,
max(Case when key = 'Description' then Value else null end)
max(case when key = 'type' the value else null end)
from table
group by Index

But given my value column is a string this will not work for my use case. Keep in mind this Redshift so it does not have all the postgres functions. Sample Desired output:

Index, Description,type
1, Apple, Orange
2, Apple, Pickle

Your desired output does not make sense, because there is only one input row per Index value. As a result, there is no ability to group the rows into a combined value.

If, instead, your input data was:

1, Description, Apple
1, Type, Delicious
2, Description, Banana
2, Type, Big
3, Description, Pineapple
3, Type, Prickly

Then you could use a query like this:

SELECT
  index,
  MAX(CASE WHEN description = 'Description' THEN type END) as description,
  MAX(CASE WHEN description = 'Type' THEN type END) as type
FROM food
GROUP BY index

The output would be:

1   Apple      Delicious
2   Banana     Big
3   Pineapple  Prickly

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM