postgresql psql:我如何在group by query后获得聚合中的单个json列

xzv2uavs  于 2023-11-18  发布在  PostgreSQL
关注(0)|答案(2)|浏览(136)

我尝试为查询中的每个group by子句获取单行。每个SELECT输出都有一个json。我尝试这样做:

SELECT MIN(C.json_column->'key') AS Key, A.field1, B.field2
    FROM json_table AS C
    LEFT JOIN another_table AS D ON D.id=C.id
    INNER JOIN another_table2 AS A ON A.id=D.col2
    INNER JOIN another_table3 AS B on B.id=D.col3
GROUP BY (A.field1, B.field2)

字符串
这里连接无关紧要。问题是MIN(C.json_column->'key')返回:

No function matches the given name and argument types. You might need to add explicit type casts.


由于我是按2个其他字段分组的,所以我必须聚合json字段。但我只想要第一个(或任何其他)单个json行。MIN似乎对json类型不起作用。我可以使用什么?

wkyowqbh

wkyowqbh1#

您正在查找distinct on构造。Demo at db<>fiddle

SELECT DISTINCT ON(A.field1, B.field2) 
    C.json_column->'key' AS Key, A.field1, B.field2
    FROM json_table AS C
    LEFT JOIN another_table AS D ON D.id=C.id
    INNER JOIN another_table2 AS A ON A.id=D.col2
    INNER JOIN another_table3 AS B on B.id=D.col3
ORDER BY A.field1, B.field2

字符串
对于这种情况,min()/max()聚合变通方案将同样工作,但通常distinct on更通用:随着列的增加,聚合会迅速失去对每个辅助列单独排序的性能,并且它们还会产生不存在的值组合,而不是来自组的真实的样本。

2cmtqfgy

2cmtqfgy2#

操作符->将JSON元素返回为JSON,使用->>将JSON元素返回为文本,然后将其转换为整数:

SELECT MIN((C.json_column->>'key')::int) AS Key, A.field1, B.field2
    FROM json_table AS C
    LEFT JOIN another_table AS D ON D.id=C.id
    INNER JOIN another_table2 AS A ON A.id=D.col2
    INNER JOIN another_table3 AS B on B.id=D.col3
GROUP BY (A.field1, B.field2)

字符串

相关问题