遍历表以连接行

时间:2019-07-01 19:38:34

标签: sql vertica string-aggregation

我有一个结构类似的表:

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

但是会引发错误,提示用户定义的转换函数group_concat必须具有over子句

3 个答案:

答案 0 :(得分:1)

您正在寻找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;

答案 1 :(得分:1)

使用array_agg

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

我认为您在使用vertica upper时需要listagg或group_concat是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

答案 2 :(得分:0)

如前所述,在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