PostgreSQL聚合与按许多列分组

时间:2019-06-30 16:48:24

标签: postgresql

如何将此表聚合为一个单行json对象?

enter image description here

有这样的请求

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**}]

1 个答案:

答案 0 :(得分:0)

我认为我的方向错误,最终决定拆分表,所以现在一切正常: enter image description here