I want to perform multiple GROUP BY and COUNT operations on a table(or CTE) and have the output as a singe JSON.
Consider the following table in a Postgres database:
| Name | Author | Publisher | Language |
|---|---|---|---|
| Book1 | Jason | Penguin | English |
| Book2 | Jason | Macmillan | English |
| Book3 | Paul | Macmillan | English |
| Book4 | Julia | Macmillan | English |
| Book5 | Julia | Penguin | English |
This is my current SQL query
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:
{
"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. Not necessarily in any specific structure, but the information needs to be there. Basically I want an output that looks something like this:
{
"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?
distinctis not a function. Enclosing the column following the keyword is useless.