Redshift SQL 用 GROUP 逗号分隔字段

问题描述 投票:0回答:1

我想用逗号分隔一个字段的值和 GROUP BY Redshift中的另外两个字段。

样本数据。

table_schema table_name column_name 
G1           G2         a
G1           G2         b
G1           G2         c
G1           G2         d
G3           G4         x
G3           G4         y
G3           G4         z

预期输出:

table_schema table_name column_name 
G1           G2         a, b, c, d
G3           G4         x, y, z

我可以在MSSQL中这样做。

SELECT table_schema, table_name, column_name = 
    STUFF((SELECT ', ' + column_name
           FROM your_table b 
           WHERE b.table_schema = a.table_schema AND b.table_name = a.table_name
          FOR XML PATH('')), 1, 2, '')
FROM information_schema.tables t
INNER JOIN information_schema.columns c on c.table_name = t.table_name AND c.table_schema = t.table_schema
GROUP BY table_schema, table_name

而在PostgreSQL中则是:

SELECT table_schema, table_name, String_agg(column_name, ',')
FROM information_schema.tables t
INNER JOIN information_schema.columns c on c.table_name = t.table_name AND c.table_schema = t.table_schema
GROUP BY table_schema, table_name

但Redshift中并不包含 STRING_AGG 功能。

我不知道如何在Redshift中实现这个功能。

编辑

使用这里的答案是行不通的。

SELECT CUST_ID,
       LISTAGG("ORDER", ', ')
WITHIN GROUP (ORDER BY "ORDER")
OVER (PARTITION BY CUST_ID) AS CUST_ID
FROM Table
ORDER BY CUST_ID

我的版本。

SELECT t.table_name, LISTAGG("column_name", ', ')
WITHIN GROUP (ORDER BY "column_name")
OVER (PARTITION BY t.table_name) AS table_schema
FROM information_schema.columns t
ORDER BY t.table_name

它给我以下错误。

0A000: Redshift表不支持指定的类型或函数(每条INFO消息一个)。

我不明白,因为我只是从一个节点中选择。

sql amazon-redshift string-aggregation
1个回答
0
投票
SELECT t.CUST_ID, c.orders
FROM Table t JOIN
      (SELECT cust_id, LISTAGG("ORDER"::text, ', ')
WITHIN GROUP (ORDER BY "ORDER") as orders
       FROM table t
       GROUP BY cust_id
      ) c
      ON t.cust_id = c.cust_id
ORDER BY CUST_ID;
© www.soinside.com 2019 - 2024. All rights reserved.