我正在尝试在 postgres 中使用 COALESCE 函数在这样的查询中:
SELECT
id_school,
SUM(COALESCE((student->'name'->>'age'), '0')::numeric)
FROM
teachers
GROUP BY 1;
问题出在: SUM(COALESCE((student->'name'->>'age'), '0')::numeric)
我尝试使用 COALESCE,因为我收到一些空字符串和错误:类型数字的输入语法无效:“”
COALESCE 不应该解决这个铸造错误吗?我不能在 SUM 函数中使用 COALESCE 吗?
答案 0 :(得分:4)
您实际上不需要 sum 中的 coalesce()
函数,因为 sum
无论如何都会忽略 NULL 值。
您的错误不是由 NULL 值引起的,而是由空字符串引起的。
因此您需要将空字符串转换为 NULL 值。这可以在 Postgres 中使用 nullif()
来完成
SELECT id_school,
SUM(nullif(student->'name'->>'age'), '')::numeric)
FROM teachers
GROUP BY 1;
如果您还可以使用带有空格的字符串作为 JSON 值,您可能需要考虑 nullif(trim(student->'name'->>'age'), '')
答案 1 :(得分:3)
URLSession.shared.dataTaskPublisher(for: url)
.map(\.data)
.decode(type: Schedule.self, decoder: JSONDecoder())
.flatMap {
Result.Publisher(.success($0))
.zip(self.fetchLiveFeed($0.dates.first?.games.first?.link ?? ""))
}
.sink(receiveCompletion: { completion in
// ...
}, receiveValue: { (schedule, live) in
// ...
})
.store(in: &cancellables)
返回第一个非空参数。空字符串是非空的。您正在尝试将 COALESCE
转换为数值。
您可以使用 ''
在 NULLIF
中获取 null 而不是空字符串。
SQL Coalesce with empty string