1 CASE 可能是 SQL 中被误用最多的关键字之一。虽然你可能以前用过这个关键字来创建字段,但是它还具有更多用法。例如,你可以在 WHERE 子句中使用 CASE。 2 3 首先让我们看一下 CASE 的语法。在一般的 SELECT 中,其语法如下: 4 5 SELECT <myColumnSpec> = 6 CASE 7 WHEN <A> THEN <somethingA> 8 WHEN <B> THEN <somethingB> 9 ELSE <somethingE> 10 END 11 12 在上面的代码中需要用具体的参数代替尖括号中的内容。下面是一个简单的例子: 13 14 USE pubs 15 GO 16 SELECT 17 Title, 18 'Price Range' = 19 CASE 20 WHEN price IS NULL THEN 'Unpriced' 21 WHEN price < 10 THEN 'Bargain' 22 WHEN price BETWEEN 10 and 20 THEN 'Average' 23 ELSE 'Gift to impress relatives' 24 END 25 FROM titles 26 ORDER BY price 27 GO 28 29 这是 CASE 的典型用法,但是使用 CASE 其实可以做更多的事情。比方说下面的 GROUP BY 子句中的 CASE: 30 31 SELECT 'Number of Titles', Count(*) 32 FROM titles 33 GROUP BY 34 CASE 35 WHEN price IS NULL THEN 'Unpriced' 36 WHEN price < 10 THEN 'Bargain' 37 WHEN price BETWEEN 10 and 20 THEN 'Average' 38 ELSE 'Gift to impress relatives' 39 END 40 GO 41 42 你甚至还可以组合这些选项,添加一个 ORDER BY 子句,如下所示: 43 44 USE pubs 45 GO 46 SELECT 47 CASE 48 WHEN price IS NULL THEN 'Unpriced' 49 WHEN price < 10 THEN 'Bargain' 50 WHEN price BETWEEN 10 and 20 THEN 'Average' 51 ELSE 'Gift to impress relatives' 52 END AS Range, 53 Title 54 FROM titles 55 GROUP BY 56 CASE 57 WHEN price IS NULL THEN 'Unpriced' 58 WHEN price < 10 THEN 'Bargain' 59 WHEN price BETWEEN 10 and 20 THEN 'Average' 60 ELSE 'Gift to impress relatives' 61 END, 62 Title 63 ORDER BY 64 CASE 65 WHEN price IS NULL THEN 'Unpriced' 66 WHEN price < 10 THEN 'Bargain' 67 WHEN price BETWEEN 10 and 20 THEN 'Average' 68 ELSE 'Gift to impress relatives' 69 END, 70 Title 71 GO 72 73 注意,为了在 GROUP BY 块中使用 CASE,查询语句需要在 GROUP BY 块中重复 SELECT 块中的 CASE 块。 74 75 除了选择自定义字段之外,在很多情况下 CASE 都非常有用。