简体   繁体   English

如何在 Postgres 的 json_build_object() 中进行 GROUP BY 和 COUNT

[英]How to do a GROUP BY and COUNT within json_build_object() in Postgres

I want to perform multiple GROUP BY and COUNT operations on a table(or CTE) and have the output as a singe JSON.我想对表(或 CTE)执行多个GROUP BYCOUNT操作,并将 output 作为单个 JSON。

Consider the following table in a Postgres database:考虑 Postgres 数据库中的下表:

Name姓名 Author作者 Publisher出版商 Language
Book1书1 Jason杰森 Penguin企鹅 English英语
Book2书2 Jason杰森 Macmillan麦克米伦 English英语
Book3书3 Paul保罗 Macmillan麦克米伦 English英语
Book4书4 Julia Julia Macmillan麦克米伦 English英语
Book5书5 Julia Julia Penguin企鹅 English英语

This is my current SQL query这是我当前的 SQL 查询

WITH first_selection AS (
    SELECT *
    FROM books
    where language='English')
SELECT json_build_object('author_options', json_agg(DISTINCT(author)),
                         'publisher_options', json_agg(DISTINCT(publisher)))
FROM first_selection

For which I get this output:为此,我得到了这个 output:

{
    "author_options":["Jason","Paul","Julia"],
    "publisher_options":["Penguin,"Macmillan"]
}

The problem is I also need the count of books for each publisher but I keep getting an error saying that nested aggregations are not allowed.问题是我还需要每个出版商的图书数量,但我不断收到错误消息,说不允许嵌套聚合。

I need the count of books in the JSON output.我需要 JSON output 中的书籍数量。 Not necessarily in any specific structure, but the information needs to be there.不一定在任何特定的结构中,但信息需要在那里。 Basically I want an output that looks something like this:基本上我想要一个看起来像这样的 output:

{
    "author_options":["Jason","Paul","Julia"],
    "publisher_options":["Penguin,"Macmillan"],
    "publisher_details": {
                             "Penguin": 2,
                             "Macmillan": 3
                          }
}

How do I count the number of books per publisher and put the result into the JSON?如何计算每个出版商的书籍数量并将结果放入 JSON?

 create table books (Name varchar(50), Author varchar(50), Publisher varchar(50), Language varchar(50));
 
 insert into books values('Book1',  'Jason',    'Penguin',      'English');
 insert into books values('Book2',  'Jason',    'Macmillan',    'English');
 insert into books values('Book3',  'Paul',     'Macmillan',    'English');
 insert into books values('Book4',  'Julia',    'Macmillan',    'English');
 insert into books values('Book5',  'Julia',    'Penguin',      'English');

Query:询问:

 WITH first_selection AS (
     SELECT *
     FROM books
     where language='English')
 , publisherscount as
 (
 select Publisher, count(*) pcount
 from books
 group by publisher
 )
 SELECT json_build_object('author_options', json_agg(DISTINCT author),
                          'publisher_options', json_agg(DISTINCT publisher),
                          'publisher_details',(select   array_to_json(array_agg(json_build_object(publisher,pcount)))
                          from publisherscount)
                         )
 FROM first_selection

Output: Output:

json_build_object json_build_object
{author_options: [Jason, Julia, Paul], publisher_options: [Macmillan, Penguin], publisher_details: [{Macmillan: 3},{Penguin: 2}]} {author_options: [Jason, Julia, Paul], publisher_options: [Macmillan, Penguin], publisher_details: [{Macmillan: 3},{Penguin: 2}]}

db<fiddle here db<小提琴在这里

You can aggregate the publishers in a separate step and then include that into the final result:您可以在单独的步骤中聚合发布者,然后将其包含到最终结果中:

with first_selection as (
  select *
  from books
  where language = 'English'
), pub_info as (
  select json_object_agg(publisher, cnt) as details
  from (
    select publisher, count(*) as cnt
    from first_selection
    group by publisher
  ) t
)
SELECT json_build_object('author_options', json_agg(distinct author),
                         'publisher_options', json_agg(distinct publisher),
                         'publisher_details', (select details from pub_info))
FROM first_selection

Online example 在线示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用 json_agg(json_build_object(.......)) 时,如何确保 json_build_object 返回空列表 - when use json_agg(json_build_object(.......)) ,how to ensure json_build_object return empty list PostgreSQL json_build_object 嵌套 - PostgreSQL json_build_object nested json_build_object()中的大小写表达式 - Case expression in json_build_object() 在PostgreSQL中使用json_build_object和json_build_array排序json结构 - Ordering json structure using json_build_object and json_build_array in Postgresql 无法使用 json_build_object 从 postgreSQL 查询创建大型 json 对象 - Unable to create a large json object from a postgreSQL query using json_build_object PostgreSQL Json_build_object / json_agg 添加聚合级别 - PostgreSQL Json_build_object / json_agg add level of aggregation SQL,在使用 json_agg 和 json_build_object 时遇到一些问题 - SQL, having some trouble with json_agg & json_build_object 在 PostgreSQL v14.x 中使用 json_build_object 和 SELECT 语句的结果 - Using json_build_object in PostgreSQL v14.x with the result of a SELECT statement PostgresSQL 无法按 json_build_object 结果排序(从子查询获得) - PostgresSQL Cannot order by json_build_object result (got from subquery) 如何确定组内计数最高的类别? - How do I determine the category with the highest count within a group?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM