Database in case when condition then else end understanding

Database in case when condition then else end understanding

  • Database seek is the total number or based on different conditions

    select count(case when status=0 then 'done' end)as done,count(case when status=-1 then 'doing' end)as doing from t_func;
    • when conditions expressed, then value end: represents the compliance with the conditions in the corresponding assigned value
    • Case count has calculated all the values, null values ​​are automatically filtered
  • select (case column when condition then value else value) from tablename value classification can be selected from

    • example:
create table t_users (id int,name varchar(20),sex int);
insert into t_users(id,name) values(1,'张一');
insert into t_users(id,name,sex) values(2,'张二',1);
insert into t_users(id,name) values(3,'张三');
insert into t_users(id,name) values(4,'张四');
insert into t_users(id,name,sex) values(5,'张五',2);
insert into t_users(id,name,sex) values(6,'张六',1);
insert into t_users(id,name,sex) values(7,'张七',2);
insert into t_users(id,name,sex) values(8,'张八',1);
select * from t_users;
select id,name,(case when sex=1 then '男' when sex=2 then '女' else '空的' end) 性别 from t_users
  • t_users table of contents:

    1 "张一"   [null]
    2 "张二"    1
    3 "张三"   [null]
    4 "张四"   [null]
    5 "张五"    2
    6 "张六"    1
    7 "张七"    2
    8 "张八"    1
  • search result:

    1 "张一"    "空的"
    2 "张二"    "男"
    3 "张三"    "空的"
    4 "张四"    "空的"
    5 "张五"    "女"
    6 "张六"    "男"
    7 "张七"    "女"
    8 "张八"    "男"

Guess you like

Origin www.cnblogs.com/MyUniverse/p/11567452.html