DB2数据库decode()函数的用法

一、按照字段内容分组;

闲话少说

1.创建表T1:sql语句如下

create table t1(
  id integer not null primary key,
  name varchar(10),
  job varchar(10)
);

2.插入部分数据:

insert into t1 values(1,'jack','vp');
insert into t1 values(2,'tony','ceo');
insert into t1 values(3,'merry','vp');
insert into t1 values(4,'linda','operation');
insert into t1 values(5,'james','operation');

例子:统计‘vp’及以上的职位的人数和普通员工的人数?

奉上sql语句如下:

select decode(job,'vp','vp_ceo','ceo','vp_ceo','operation'),count(*) job_count from t1 group by decode(job,'vp','vp_ceo','ceo','vp_ceo','operation');

二、按照字段内容排序;

1.创建表T2;sql语句如下:

create table t2(
  id integer not null primary key,
  dept_name varchar(10),
  region_id integer
);

2.插入数据:

insert into t2 values(1,'deptA',12);
insert into t2 values(2,'deptA',10);
insert into t2 values(3,'deptA',9);
insert into t2 values(4,'deptA',7);
insert into t2 values(5,'deptB',12);
insert into t2 values(6,'deptB',13);
insert into t2 values(7,'deptB',22);
insert into t2 values(8,'deptB',9);
insert into t2 values(9,'deptC',8);
insert into t2 values(10,'deptC',10);
insert into t2 values(11,'deptC',11);

例子1:按部门dept_name排序(A->B->C)排序,对每个部门内部按照dept升序?

select * from t2 order by decode(dept_name,'deptA',1,'deptB',2,'deptC',3),region_id;

DB2数据库decode()函数的用法_第1张图片

例子2;若dept_name为deptA,则按照id升序排列,否则按照region_id升序排列?

select * from t2 order by decode(dept_name,'deptA',id,region_id);

DB2数据库decode()函数的用法_第2张图片

你可能感兴趣的:(数据库)