Postgresql聚合数组
嗨,我有两张桌子
Student -------- Id Name 1 John 2 David 3 Will Grade --------- Student_id Mark 1 A 2 B 2 B+ 3 C 3 A
是否有可能使本机Postgresqlselect像这样的结果:
Name Array of marks ----------------------- 'John', {'A'} 'David', {'B','B+'} 'Will', {'C','A'}
但不是这样
Name Mark ---------------- 'John', 'A' 'David', 'B' 'David', 'B+' 'Will', 'C' 'Will', 'A'
使用array_agg: http ://www.sqlfiddle.com/#!1 / 5099e /1
SELECT s.name, array_agg(g.Mark) as marks FROM student s LEFT JOIN Grade g ON g.Student_id = s.Id GROUP BY s.Id
顺便说一下,如果您使用的是Postgres 9.1, 则不需要重复 SELECT到GROUP BY上的列,例如,您不需要在GROUP BY上重复学生名称。 您只能在主键上使用GROUP BY。 如果您删除学生的主键,则需要在GROUP BY上重复学生姓名。
CREATE TABLE grade (Student_id int, Mark varchar(2)); INSERT INTO grade (Student_id, Mark) VALUES (1, 'A'), (2, 'B'), (2, 'B+'), (3, 'C'), (3, 'A'); CREATE TABLE student (Id int primary key, Name varchar(5)); INSERT INTO student (Id, Name) VALUES (1, 'John'), (2, 'David'), (3, 'Will');
我理解你可以做这样的事情:
SELECT p.p_name, STRING_AGG(Grade.Mark, ',' ORDER BY Grade.Mark) As marks FROM Student LEFT JOIN Grade ON Grade.Student_id = Student.Id GROUP BY Student.Name;
编辑
我不确定。 但也许这样的事情:
SELECT p.p_name, array_to_string(ARRAY_AGG(Grade.Mark),';') As marks FROM Student LEFT JOIN Grade ON Grade.Student_id = Student.Id GROUP BY Student.Name;
在这里引用
您可以使用以下内容:
SELECT Student.Name as Name, (SELECT array(SELECT Mark FROM Grade WHERE Grade.Student_id = Student.Id)) AS ArrayOfMarks FROM Student
如下所述: http : //www.mkyong.com/database/convert-subquery-result-to-array/