添加列值的Case语句

时间:2012-04-11 02:39:48

标签: sql sql-server-2008 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

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

使用COELESCE(value,0)使null为零

答案 2 :(得分: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