json - 计算所有行并在单个 json 对象中显示有限数量的行

标签 json postgresql aggregate-functions

我的查询是

select array_to_json(array_agg(row_to_json(t))) from (
    select count(*) over() as total, id,title
    FROM notifications 
    WHERE  title ilike '%a%'
LIMIT 5 OFFSET 1)t

输出是

[
    {
        "title": "Sartaj                                                              ", 
        "id": 3,
        "total":16
    }
]

结果包括对象中的总数,但我想将其移到对象之外。

我期望的答案是

[
    "total":16,
    "data":[
{
        "title": "Sartaj                                                       ", 
        "id": 3
    }]
 ]

我也试过

with tmp_notifications as (
    SELECT id,title,description,img_url,link,created_on from notifications 
    where title ilike '%universi%'
    ) 
    select row_to_json(t) from (
        select count(*) as data_count,
        (json_agg(json_build_object('description',description,'title',title,'created_on',created_on,
        'link',link,'img_url',img_url,'id',id)) 
         ) as data from tmp_notifications limit 1
        )t

但限制在这里不起作用。

最佳答案

使用json_build_object()json_agg() :

select json_build_object('total', count(*), 'data', json_agg(to_json(t)))
from (
    select id, title
    from notifications 
    where  title ilike '%a%'
    ) t

请参阅 DbFiddle. 中的完整示例


您可以使用 WITH 语句来计算所有过滤的行,但只显示有限的行数,例如:

with filtered as (
    select id, title
    from notifications 
    where title ilike '%a%'
)

select json_build_object(
    'total', (select count(*) from filtered), 
    'data', json_agg(to_json(t)))
from (
    select id, title
    from filtered
    order by id
    limit 2
    ) t

DbFiddle.

关于json - 计算所有行并在单个 json 对象中显示有限数量的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49840983/

相关文章:

json - 是否可以 'inject' 引用 JSON 架构

json - 编码为 JSON 的对象的大小(以位为单位)?

java - Jettison 或 Kryo

java - 为什么我从 Java 批量执行 PostgreSQL 上的存储过程时收到错误通知 "a result was not expected"?

sql - 类似字符串的 PostgreSQL 搜索列

php - 如何使用 json api 将 Lat Long 转换为 php 中的地址?

postgresql - 一秒钟内根据多行更新一个表中的多行

Postgresql 显式 VACUUM 与自动 VACUUM : Differences? 建议?

MySQL Min()、MAX() 使用另一个表中的 ID

php - 计数项目或递增数字?