programing tip

Postgresql 집계 배열

itbloger 2020. 9. 25. 07:37
반응형

Postgresql 집계 배열


안녕하세요 저는 두 개의 테이블이 있습니다

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

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

네이티브 Postgresql을 선택하여 다음과 같은 결과를 얻을 수 있습니까?

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/


@Michael Buen got it right. I got what I needed using array_agg.

Here just a basic query example in case it helps someone:

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

And the result was something like:

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


This post also helped me a lot: "Group By" in SQL and Python Pandas. It basically says that it is more convenient to use only SQL when possible, but that Python Pandas can be useful to achieve extra functionalities in the filtering process.

I hope it helps

참고URL : https://stackoverflow.com/questions/10928210/postgresql-aggregate-array

반응형