我有以下数据库:
paperid | authorid | name | affiliation
---------+----------+------------------+---------------------------------------------------------------------------------
487792 | 1487835 | Mark A. Magnuson | Vanderbilt University
487792 | 1814994 | Miriam Magnuson | Department of Education and Psychology, Linköping University, Linköping, Sweden
487792 | 2248713 | Leif Hergils | Department of Audiology, University Hospital, Linköping, Sweden
我想用它制作这样的东西:
paperid | name |
---------+---------------------------------------------------------+
487792 | Mark A. Magnuson Miriam Magnuson Leif Hergils
将所有作者的姓名放在一个列/字段中。
如何使用SQL执行此操作?
修改
我试过了:
select paperid, concat(name) as authors FROM newpaperauthor GROUP BY paperid, name ORDER BY paperid;
但这将分别列出作者:
paperid | authors
---------+----------------------------
896450 | Bart Dhoedt
896450 | Marc De Leenheer
答案 0 :(得分:4)
select paperid, string_agg(name, ' ') as authors
FROM newpaperauthor
GROUP BY paperid
ORDER BY paperid;
string_agg
通过聚合列进行字符串连接:
http://www.postgresql.org/docs/current/static/functions-aggregate.html#FUNCTIONS-AGGREGATE-TABLE
concat
对提供的参数进行字符串连接:
http://www.postgresql.org/docs/current/static/functions-string.html#FUNCTIONS-STRING-OTHER
答案 1 :(得分:0)
concat(x,y)
将两个标量值粘合在一起(例如,同一行中的两个列值)。 string_agg(name,sep)将一个聚合组中的列name
的值粘合在一起。由于无法保证在该组内进行排序,因此请注意;并查看SQL-2003级聚合,例如PARTITION
,您可以在其中指定订单。