是否可以在 SUM 函数中使用 COALESCE 函数?

Lua*_*res 0 sql postgresql

我试图在 postgres 的查询中使用 COALESCE 函数,如下所示:

SELECT 
  id_school,
  SUM(COALESCE((student->'name'->>'age'), '0')::numeric)
FROM
  teachers
GROUP BY 1;
Run Code Online (Sandbox Code Playgroud)

问题在于: SUM(COALESCE((student->'name'->>'age'), '0')::numeric)

我尝试使用 COALESCE,因为我收到了一些空字符串和 ERROR: invalid input syntax for type numeric: ""

COALESCE 不应该解决这个铸造错误吗?我不能在 SUM 函数中使用 COALESCE 吗?

a_h*_*ame 5

您实际上并不需要coalesce()sum 中的函数,因为sum无论如何都会忽略 NULL 值。

您的错误不是由 NULL 值引起的,而是由空字符串引起的。

因此,您需要将空字符串转换为 NULL 值。这可以nullif()在 Postgres 中使用

SELECT id_school,
       SUM(nullif(student->'name'->>'age'), '')::numeric)
FROM teachers
GROUP BY 1;
Run Code Online (Sandbox Code Playgroud)

如果您还可以使用带有空格的字符串作为 JSON 值,您可能需要考虑 nullif(trim(student->'name'->>'age'), '')