【问题标题】:How to get a json which is distinct of columns如何获得与列不同的json
【发布时间】:2020-05-27 09:49:28
【问题描述】:

我有一个PostgreSQL数据库表,内容如下:

id | person_key | age | gender | email
1  | 1          | 25  | M      | test@mail.com
2  | 1          | 25  | M      | test_2@gmail.com
3  | 2          | 35  | F      | sample_2@gmail.com
4  | 1          | 25  | M      | test_3@gmail.com

我正在寻找一种获取 json 输出的方法,如下所示:

person_key.   | json

    1         | {'age':25, 'gender':'M', 'email':['test@mail.com','test_2@gmail.com','test_3@gmail.com' ]} 
    2         | {'age':35, 'gender':'F', 'email':['sample_2@gmail.com' ]} 

【问题讨论】:

    标签: sql arrays json database postgresql


    【解决方案1】:

    您可以使用聚合和 Postgres json 函数:

    select 
        person_key,
        json_build_object(
            'age', age,
            'gender', gender,
            'email', json_agg(email order by id)
        ) js
    from mytable
    group by person_key, age, gender
    order by person_key
    

    Demo on DB Fiddle

    人键 | js ---------: | :------------------------------------------------ ----------------------------------------------------------- 1 | {“年龄”:25,“性别”:“M”,“电子邮件”:[“test@mail.com”,“test_2@gmail.com”,“test_3@gmail.com”]} 2 | {“年龄”:35,“性别”:“F”,“电子邮件”:[“sample_2@gmail.com”]}

    【讨论】:

      猜你喜欢
      • 2013-06-22
      • 2020-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-12
      • 2021-08-15
      • 1970-01-01
      相关资源
      最近更新 更多