gpt4 book ai didi

sql - 在 Redshift 中将多行转换为列

转载 作者:行者123 更新时间:2023-11-29 13:27:38 25 4
gpt4 key购买 nike

我正在使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com