【问题标题】:Pivot multiple rows into columns in Redshift在 Redshift 中将多行转换为列
【发布时间】:2015-06-19 14:18:46
【问题描述】:

我正在使用 aws redshift 并且有一个案例,我有多个行作为唯一 ID,并且需要使用 SQL 将行组合成每个唯一 ID 的一列。我已经搜索了如何做到这一点,它看起来在 postgres 中是可能的,但是,建议的方法使用如下函数:string_agg 和 array_agg 在 aws 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 |          |        |        |
+----+----------+---------+-------+----------+--------+--------+

【问题讨论】:

    标签: sql postgresql select amazon-web-services amazon-redshift


    【解决方案1】:

    如果您的示例数据表明您的数据,并且每个 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# 之类的东西启动一个简单的控制台应用程序,读入数据并写出一个新表。

    【讨论】:

    • 谢谢!!这真的很有帮助
    猜你喜欢
    • 1970-01-01
    • 2018-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-27
    相关资源
    最近更新 更多