简体   繁体   中英

sql - GROUP_CONCAT in PostgreSQL 9.6

I have a table and I'd like to pull one row per id with field values concatenated.

In my table, for example, I have this:

SELECT objects.id, objects.title, categories.name,
       (SELECT COUNT(0) FROM comments WHERE comments.object_id = objects.id) as count
FROM objects 
LEFT JOIN restaurant_properties ON restaurant_properties.object_id = objects.id
LEFT JOIN categories on categories.id = restaurant_properties.category_id
WHERE type_id = 2 


id | title      | category_name | count |

12 | Tosca      | Cafe          | 0     |
12 | Tosca      | Bar           | 0     |
12 | Tosca      | Pizza         | 0     |
11 | Green Cafe | Cafe          | 0     |
11 | Green Cafe | Tea House     | 0     |

And I'd like to output:

id | title      | category_name    | count |

12 | Tosca      | Cafe, Bar, Pizza | 0     |
11 | Green Cafe | Cafe, Tea House  | 0     |

When I use GROUP BY "name", it gives me an error:

[Err] ERROR: the "objects.id" column must appear in a GROUP BY clause or used in an aggregate function

An aggregation query should work, with STRING_AGG() :

SELECT o.id, o.title, STRING_AGG(c.name, ', ') as categories,
       (SELECT COUNT(*) FROM comments co WHERE co.object_id = o.id) as count
FROM objects o LEFT JOIN 
     restaurant_properties rp
     ON rp.object_id = o.id LEFT JOIN
     categories c
     ON c.id = rp.category_id
WHERE type_id = 2 
GROUP BY o.id, o.title

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM