我正在使用 aws redshift,并且有一种情况,我有多个行用于唯一 ID,并且需要使用 SQL 将行合并为每个唯一 ID 的一列。我已经搜索了如何执行此操作,看起来在 postgres 中是可能的,但是,建议的方法使用诸如 string_agg 和 array_agg 之类的函数,这些函数在 aws redshift 中不可用。使用 Redshift 可以实现这一点吗?有谁知道不使用函数来解决这个问题的方法吗?
这就是我正在处理的内容。下表表示查询,该查询为我提供了需要将每个 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 | | | |
+----+----------+---------+-------+
我希望最终得到什么:
+----+----------+---------+-------+----------+---------+-------+
| 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 | | | |
+----+----------+---------+-------+----------+--------+--------+
最佳答案
如果您的示例数据代表您的数据,并且每个 id 最多只有两个条目,那么您可以直接加入自身以获得您请求的输出:
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
如果您有两个以上,您可以使用 C# 等语言启动一个简单的控制台应用程序,读取数据并将其写入新表。
关于sql - 在 Redshift 中将多行透视为列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30940467/