PostgreSQL聚合数组

llew8vvj  于 2023-06-29  发布在  PostgreSQL
关注(0)|答案(4)|浏览(115)

我有两张table

Student
--------
Id  Name
1   John    
2   David
3   Will

Grade
---------
Student_id  Mark
1           A
2           B
2           B+
3           C
3           A

是否可以使用本地PostgreSQL SELECT来获得如下结果:

Name    Array of marks
-----------------------
'John',     {'A'}
'David',    {'B','B+'}
'Will',     {'C','A'}

像下面这样

Name    Mark
----------------
'John',     'A'
'David',    'B'
'David',    'B+'
'Will',     'C'
'Will',     'A'
62o28rlo

62o28rlo1#

使用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上的列don't need to repeat到GROUP BY,例如:你不需要在GROUP BY上重复学生的名字。只能在主键上GROUP BY。如果删除student上的主键,则需要在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');
piztneat

piztneat2#

据我所知,你可以这样做:

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;

参考here

niwlg2el

niwlg2el3#

您可以使用以下命令:

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/

fnatzsnv

fnatzsnv4#

Michael Buen做对了。我使用array_agg得到了我需要的东西。
这里只是一个基本的查询示例,以防它帮助某人:

SELECT directory, ARRAY_AGG(file_name) 
FROM table 
WHERE type = 'ZIP' 
GROUP BY directory;

结果是这样的:

|     parent_directory    |                 array_agg              |  
+-------------------------+----------------------------------------+
| /home/postgresql/files  | {zip_1.zip,zip_2.zip,zip_3.zip}        |
| /home/postgresql/files2 | {file1.zip,file2.zip}                  |

这篇文章也帮了我很多:"Group By" in SQL and Python Pandas。它基本上是说,如果可能的话,只使用PSQL会更有效,但是Python Pandas可以在过滤过程中实现额外的功能。

相关问题