循环 Table 以连接行

Loop Through a Table to concatenate Rows

我有一个类似结构的table:

Name Movies_Watched
A    Terminator
B    Alien
A    Batman
B    Rambo
B    Die Hard

....

我想得到这个:

Name  Movies_Watched
A     Terminator;Batman
B     Alien, Die Hard, Rambo

我最初的猜测是:

SELECT Name, Movies_Watched || Movies_Watched from TABLE

但显然这是错误的。有人能告诉我如何遍历第二列并将它们连接起来吗?逻辑是怎样的?

知道 group_concat 是正确的方法。但是还没有弄清楚。当我尝试过时:

select name, group_concat(movies_watched) from table group by 1

但是它抛出一个错误说 User-defined transform function group_concat must have an over clause

您正在寻找string_agg()

select name, string_agg(movie_watched, ';') as movies_watched
from t
group by name;

就是说,您正在使用 Postgres,因此您应该学习如何使用数组而不是字符串来处理这些事情。例如,当电影名称中有分号时,就不会与数组混淆。那将是:

select name, array_agg(movie_watched) as movies_watched
from t
group by name;

使用array_agg

SELECT Name, array_agg(Movies_Watched)
FROM data_table
GROUP BY Name

我认为你需要 listagg 或 group_concat 因为你使用的是 vertica upper 是 postgrey 解决方案

SELECT Name, listagg(Movies_Watched) 
FROM data_table
GROUP BY Name

 select Name, 
 group_concat(Movies_Watched) over (partition by Name order by name) ag
 from mytable

如前所述,在 Vertica 中是 LISTAGG():

WITH
input(nm,movies_watched) AS (
          SELECT 'A','Terminator'
UNION ALL SELECT 'B','Alien'
UNION ALL SELECT 'A','Batman'
UNION ALL SELECT 'B','Rambo'
UNION ALL SELECT 'B','Die Hard'
)
SELECT
  nm AS "Name"
, LISTAGG(movies_watched) AS movies_watched
FROM input
GROUP BY nm;
-- out  Name |    movies_watched    
-- out ------+----------------------
-- out  A    | Terminator,Batman
-- out  B    | Alien,Rambo,Die Hard
-- out (2 rows)
-- out 
-- out Time: First fetch (2 rows): 12.735 ms. All rows formatted: 12.776 ms