gpt4 book ai didi

sql - 如何将多列分组为单个数组或类似数组?

转载 作者:行者123 更新时间:2023-11-29 12:50:41 24 4
gpt4 key购买 nike

我希望我的查询返回结构如下的结果,其中 tags 是数组数组或类似数组:

id | name | tags
1 a [[1, "name1", "color1"], [2, "name2", color2"]]
2 b [[1, "name1", "color1"), (3, "name3", color3"]]

我希望这个查询能够工作,但它给了我一个错误:

SELECT  i.id, i.name, array_agg(t.tag_ids, t.tag_names, t.tag_colors) as tags 
FROM ITEMS
LEFT OUTER JOIN (
SELECT trm.target_record_id
, array_agg(tag_id) as tag_ids
, array_agg(t.tag_name) as tag_names
, array_agg(t.tag_color) as tag_colors
FROM tags_record_maps trm
INNER JOIN tags t on t.id = trm.tag_id
GROUP BY trm.target_record_id
) t on t.target_record_id = i.id;

错误:

PG::UndefinedFunction: ERROR:  function array_agg(integer[], character varying[], character varying[]) does not exist
LINE 1: ..., action_c2, action_c3, action_name, action_desc, array_agg(...
HINT: No function matches the given name and argument types. You might need to add explicit type casts.

这个查询有效并产生类似的结果(但不是我想要的):

SELECT  i.id, i.name, t.tag_ids, t.tag_names, t.tag_colors as tags  as tags 
FROM ITEMS
LEFT OUTER JOIN (
SELECT trm.target_record_id, array_agg(tag_id) as tag_ids, array_agg(t.tag_name) as tag_names, array_agg(t.tag_color) as tag_colors
FROM tags_record_maps trm
INNER JOIN tags t on t.id = trm.tag_id
GROUP BY trm.target_record_id
) t on t.target_record_id = i.id;

结果:

id | name | tag_ids | tag_names         | tag_colors          
1 a [1, 2] ["name1, "name2"] ["color1", "color2"]
1 a [1, 3] ["name1, "name3"] ["color1", "color3"]

编辑:

此查询几乎生成了我正在寻找的内容,除了它命名为 json 键 f1f2f3。如果我能将它们命名为 idnamecolor 就完美了:

  SELECT        trm.target_record_id, json_agg( (t.id, t.tag_name, t.tag_color) )
FROM tags_record_maps trm
INNER JOIN tags t on t.site_id = trm.site_id and t.id = trm.tag_id
GROUP BY trm.target_record_id
having count(*) > 1;

结果:

[{"f1":1,"f2":"name1","f3":"color1"},{"f1":2,"f2":"name2","f3":"color2"}]

最佳答案

(t.id, t.tag_name, t.tag_color)ROW(t.id, t.tag_name, t.tag_color) 的简短语法 - 和一个ROW constructor不保留嵌套的属性名称。 The manual:

By default, the value created by a ROW expression is of an anonymous record type. If necessary, it can be cast to a named composite type —either the row type of a table, or a composite type created withCREATE TYPE AS.

大胆强调我的。要在结果中也获得正确的键名,请按照引用中的建议转换到已注册的复合类型,使用嵌套子选择,或简单地使用json_build_object()在 Postgres 9.4 或更新版本中(有效地避免先验的 ROW 构造函数):

SELECT trm.target_record_id
, <b>json_agg(json_build_object('id', t.id
, 'tag_name', t.tag_name
, 'tag_color', t.tag_color)) AS tags</b>
FROM tags_record_maps trm
JOIN tags t USING (site_id)
WHERE t.id = trm.tag_id
GROUP BY trm.target_record_id
HAVING count(*) > 1;

我使用原始的列名,但您可以自由选择您的键名。在你的情况下:

       json_agg(json_build_object('id', t.id
, 'name', t.tag_name
, 'color', t.tag_color)) AS tags

详细解释:

关于sql - 如何将多列分组为单个数组或类似数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54637699/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com