当前位置: 移动技术网 > IT编程>数据库>MSSQL > case when

case when

2019年06月05日  | 移动技术网IT编程  | 我要评论

末日祭典,毛线编织视频,邵华整死郝明莉

 1 --case 具有两种格式: 
 2 --(1)简单 case 函数将某个表达式与一组简单表达式进行比较以确定结果。 
 3 --(2)case 搜索函数计算一组布尔表达式以确定结果。两种格式都支持可选的 else 参数。 
 4 
 5 --语法
 6 --简单 case 函数:
 7 
 8 --case input_expression
 9 --    when when_expression then result_expression
10 --        [ ...n ]
11 --    [ 
12 --        else else_result_expression
13 --    end
14 
15 --case 搜索函数:
16 
17 select case statusvalue
18             when '0' then (select top 1 字段名 from work)
19             when '1' then (select top 1 字段名 from notice) end
20   from commonstatusdict;
21 
22 
23 create table tb (id int,
24                  class varchar); --class种类就只有三种,如果不固定就需要存储过程来实现
25 insert tb
26 select 1,
27        'a'
28 union all
29 select 1,
30        'a'
31 union all
32 select 1,
33        'b'
34 union all
35 select 1,
36        'c'
37 union all
38 select 2,
39        'a'
40 union all
41 select 2,
42        'b'
43 union all
44 select 2,
45        'b';
46 select *
47   from tb;
48 
49 --想查找出按id分组得到的 a  ,b  ,c 的数量
50 --  如下
51 --id   a   b    c
52 --1   2   1     1
53 --2   1   2    0 
54 
55 
56 select id,
57        a = sum(case class
58                     when 'a' then 1
59                     else 0 end),
60        b = sum(case class
61                     when 'b' then 1
62                     else 0 end),
63        c = sum(case class
64                     when 'c' then 1
65                     else 0 end)
66   from tb
67  group by id;

 


 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网