除法结果为零时返回字符串

时间:2014-06-07 07:47:37

标签: sql postgresql null case coalesce

我有一个像这样的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。

2 个答案:

答案 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