带有伪行的json_agg()

时间:2018-12-15 09:07:17

标签: json postgresql aggregate-functions

CREATE TABLE content
(
    code          INTEGER NOT NULL
  , nameid        TEXT    NOT NULL
)

INSERT INTO content(code, nameid) VALUES
  ( 0, 'Support')
, ( 1, 'Adrenaline')
, ( 2, 'Aquapark')
;

需要选择所有内容作为名为'content'的JSON数组对象,其伪行的代码为''和nameid ='All'

我做了什么:
1)简单选择

SELECT 
   json_build_object('content', (SELECT json_agg(json_build_object(
    'code',   s.code::TEXT
  , 'nameid', s.nameid::TEXT
  ))
  FROM content s
  )
);

结果是

{
    "content": [{
            "code": "0",
            "nameid": "Support"
        },
        {
            "code": "1",
            "nameid": "Adrenaline"
        },
        {
            "code": "2",
            "nameid": "Aquapark"
        }
    ]
}

很好,但是如何添加伪行?
2)我能做到的最好

SELECT  
  json_build_object('content', json_build_array(
    json_build_object(
      'code',   ''
    , 'nameid', 'All'::TEXT),    
    (SELECT json_agg(json_build_object(
      'code',   s.code::TEXT
    , 'nameid', s.nameid::TEXT
  ))
  FROM content s
  ))
);

结果是

{
    "content": [{
            "code": "",
            "nameid": "All"
        },
        [{
                "code": "0",
                "nameid": "Support"
            },
            {
                "code": "1",
                "nameid": "Adrenaline"
            },
            {
                "code": "2",
                "nameid": "Aquapark"
            }
        ]
    ]
}

我们在数组中有数组,就像在sql中一样,在json中,但是我不明白如何将json_agg与伪行结合起来。

1 个答案:

答案 0 :(得分:1)

使用to_json()union all

select jsonb_build_object('content', json_agg(to_json))
from (
    select to_json(c)
    from (select '' as code, 'All' as nameid) c
    union all
    select to_json(c)
    from content c
    ) s

输出:

 {
    "content": [
        {
            "code": "",
            "nameid": "All"
        },
        {
            "code": 0,
            "nameid": "Support"
        },
        {
            "code": 1,
            "nameid": "Adrenaline"
        },
        {
            "code": 2,
            "nameid": "Aquapark"
        }
    ]
 }

在派生表中带有别名的版本:

select jsonb_build_object('content', json_agg(codes))
from (
    select to_json(c) as codes
    from (select '' as code, 'All' as nameid) c
    union all
    select to_json(c)
    from content c
    ) s