Pivot multiple rows into columns in Redshift

9.2k Views Asked by At

I am working with aws redshift and have a case where I have multiple rows for a unique ID and need to use SQL to combine the rows into one column per unique ID. I've searched how to do this and it looks like it is possible in postgres, however, the suggested methods use functions like: string_agg and array_agg which are not available in aws redshift. Is this even possible using redshift? Does anyone know ways to attack this problem without using functions?

Here's What I am working with. The table below represent the query that gives me the rows I need to form into one column per ID:

+----+----------+---------+-------+
| ID | make     | model   | type  |
+----+----------+---------+-------+
| 1  | ford     | mustang | coupe | 
| 1  | toyota   | celica  | coupe | 
| 2  | delorean | btf     | coupe |
| 2  | mini     | cooper  | coupe |
| 3  | ford     | mustang | coupe |
| 3  |          |         |       |
+----+----------+---------+-------+

What I am hoping to end up with:

+----+----------+---------+-------+----------+---------+-------+
| ID | make     | model   | type  | make     | model   | type  |
+----+----------+---------+-------+----------+---------+-------+
| 1  | ford     | mustang | coupe | toyota   | celica | coupe  |
| 2  | delorean | bttf    | coupe | mini     | cooper | coupe  |
| 3  | ford     | mustang | coupe |          |        |        |
+----+----------+---------+-------+----------+--------+--------+
1

There are 1 best solutions below

0
On BEST ANSWER

If your sample data is indicative of your data and you will only have max two entries per id then you could just join on itself to get the output you have requested:

select id, a.make, a.model, a.type, b.make, b.model, b.type
from yourtable a
  left outer join yourtable b
  on b.id = a.id 
  and b.make != a.make
  and b.model != a.model
  and b.type != a.type

If you have more than two, you could spin up a simple console app in something like c#, read in the data and write out to a new table.