我有一个像这样的SQL查询:
SELECT
u.id,
tu.score/(CASE tu.mo_count WHEN 0 THEN NULL ELSE tu.mo_count END) AS score_avg
FROM tournament_userscore tu
INNER JOIN users u ON u.id = tu.user_id
WHERE tournament_id = 1
ORDER BY tu.score DESC
当tu.mo_count
为零时,Null已被替换而不是零。如何为此行设置'EMPTY'
之类的字符串:
tu.score/(CASE tu.mo_count WHEN 0 THEN NULL ELSE tu.mo_count END) AS score_avg
我的意思是当分割结果为 零 或 为空 时,我想返回“任何内容“string。
答案 0 :(得分:2)
如果您不想使用CASE,可以使用NULLIF和COALESCE:
SELECT
u.id,
COALESCE(tu.score/NULLIF(tu.mo_count, 0), 0) AS score_avg
FROM tournament_userscore tu
INNER JOIN users u ON u.id = tu.user_id
WHERE
tournament_id = 1
ORDER BY
tu.score DESC;
答案 1 :(得分:1)
尝试将CASE
- 语句移到外面:
SELECT
u.id,
CASE WHEN tu.mo_count = 0 THEN 'EMPTY' ELSE (tu.score/tu.mo_count)::text END as score_avg
FROM tournament_userscore tu
INNER JOIN users u ON u.id = tu.user_id
WHERE tournament_id = 1
ORDER BY tu.score DESC