我有一个这样的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
为零时,将替换空值而不是零。如何为此行设置类似'EMPTY'
的字符串:tu.score/(CASE tu.mo_count WHEN 0 THEN NULL ELSE tu.mo_count END) AS score_avg
我的意思是当除法结果为零或为空时,我想返回“anything”字符串。
最佳答案
尝试将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