如何将此表聚合为一个单行json对象?
有这样的请求
select
tb.book_id,
json_agg(json_build_object('id', t.id, 'name', t.name, 'likes', tb.likes) order by tb.likes desc) as tags
from
tags_books as tb
join
tags as t on tb.tag_id = t.id
where
tb.book_id = 2
group by
tb.book_id
结果:
[{"id" : 2, "name" : "Для взрослых", "likes" : 3}, {"id" : 3, "name" : "Приключения", "likes" : 2}, {"id" : 1, "name" : "Экшн", "likes" : 1}, **{"id" : 4, "name" : "Комедия", "likes" : 1}, {"id" : 4, "name" : "Комедия", "likes" : 1}**]
我几乎得到了想要的东西,但是我需要以某种方式将两个标签聚合到一起(最后一行'Комедия')并获得喜欢的总和。
结果应如下所示:
[{"id" : 2, "name" : "Для взрослых", "likes" : 3}, {"id" : 3, "name" : "Приключения", "likes" : 2}, {"id" : 1, "name" : "Экшн", "likes" : 1}, {"id" : 4, "name" : "Комедия", "likes" : **2**}]