我试图为查询中的每个 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 类型。我可以用什么?
distinct on
结构:
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
这会为每对独特的
json_column
选择一个 (A.field1, B.field2)
,丢弃其余的。
->
将 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)