Concatenate multiple rows in an array with SQL on PostgreSQL

后端 未结 4 1937
挽巷
挽巷 2020-12-13 17:45

I have a table constructed like this :

oid | identifier | value
1   | 10         | 101
2   | 10         | 102
3   | 20         | 201
4   | 20         | 202
5         


        
4条回答
  •  臣服心动
    2020-12-13 18:16

    Simple example: each course have many lessons, so if i run code below:

    SELECT
      lessons.course_id AS course_id,
      array_agg(lessons.id) AS lesson_ids
    FROM lessons
    GROUP BY
      lessons.course_id
    ORDER BY
      lessons.course_id
    

    i'd get next result:

    ┌───────────┬──────────────────────────────────────────────────────┐
    │ course_id │                   lesson_ids                         │
    ├───────────┼──────────────────────────────────────────────────────┤
    │         1 │ {139,140,141,137,138,143,145,174,175,176,177,147,... │
    │         3 │ {32,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,... │
    │         5 │ {663,664,665,649,650,651,652,653,654,655,656,657,... │
    │         7 │ {985,984,1097,974,893,971,955,960,983,1045,891,97... │
    │       ...                                                        │
    └───────────┴──────────────────────────────────────────────────────┘
    

提交回复
热议问题