5

我需要写一个将返回的 case 语句

“1 of 3” if someone voted in one of three elections, 
“2 of 3” if someone voted in two of three elections, 
“3 of 3” if someone voted in three of three elections, 

问题是有些值是 varchar,有些是 null,我无法将它们加在一起。这是我的想法,但我无法让它发挥作用。

select 
id,
CASE 
     WHEN race1 + race2 + race3 = 0 then '0-3'
     WHEN race1 + race2 + race3 = 1 then '1-3'
     WHEN race1 + race2 + race3 = 2 then '2-3'
     WHEN race1 + race2 + race3 = 3 then '3-3'
     WHEN race1 + race2 + race3 is null then 'Unknown'
 END AS General_Turnout
from test4

http://sqlfiddle.com/#!3/cac66/3

4

3 回答 3

9

这应该有效:

select 
id,
    CAST( (CASE WHEN race1 IS NOT NULL THEN 1 ELSE 0 END)
   +(CASE WHEN race2 IS NOT NULL THEN 1 ELSE 0 END)
   +(CASE WHEN race3 IS NOT NULL THEN 1 ELSE 0 END) AS CHAR) + '-3'
AS General_Turnout
from test4
于 2012-04-11T02:47:05.570 回答
0

使用 COELESCE(value,0) 以便将 null 视为零

于 2012-04-11T02:45:32.607 回答
0

根据您在 SQLfiddle 上发布的内容,我假设 NULL 表示没有投票,任何字符串都表示确实投票。您不能在race1、race2 和race3 列中添加非数字字符串,但这应该可以:

SELECT 
  id,
  CAST(
    CASE WHEN race1 IS NOT NULL then 1 ELSE 0 END +
    CASE WHEN race2 IS NOT NULL then 1 ELSE 0 END +
    CASE WHEN race3 IS NOT NULL then 1 ELSE 0 END
  AS CHAR) + '-3' AS General_Turnout
FROM test4
于 2012-04-11T04:41:13.100 回答