select * from tt1;
ID datatype icount
--- ---------- ----------
1 1 22
2 2 22
3 3 22
1 2 22
1 3 22
1 4 22
1 5 22
1 6 22
2 1 22
....
.....
.......
create table tt1(id number ,datatype number,icount number);
insert into tt1 values(1,1,22);
insert into tt1 values(2,1,22);
insert into tt1 values(3,1,22);
insert into tt1 values(4,1,22);
insert into tt1 values(1,2,22);
insert into tt1 values(1,3,22);
insert into tt1 values(1,5,22);
insert into tt1 values(1,6,22);
insert into tt1 values(2,2,22);
insert into tt1 values(3,2,22);
insert into tt1 values(3,3,22);
insert into tt1 values(2,5,22);
查询各个id的数据类型的总数,需求为:
各个 id 的 数据类型为 1 或 2 的总数, 数类型为3 或4 的总数,数据类型为5 或 6 的总数
实验一:
select id,sum(case dtype when 1 then icount else 0 end) "定位",sum(case dtype when 2 then icount else 0 end) "调位",
sum(case dtype when 3 then icount else 0 end) "通告"
from
(
with sss as (select * from tt1 )
select id,1 dtype,sum(icount) icount from sss where datatype in (1,2) group by id
union all
select id,2 dtype,sum(icount) icount from sss where datatype in (3,4) group by id
union all
select id,3 dtype,sum(icount) icount from sss where datatype in (5,6) group by id
) group by id;
ID 定位 调位 通告
---------- ---------- ---------- ----------
1 44 44 44
2 44 0 44
3 44 22 0
实验二:
select id,sum(case when datatype in (1,2) then icount else 0 end) "定位",
sum(case when datatype in (3,4) then icount else 0 end) "调位",
sum(case when datatype in (5,6) then icount else 0 end) "通告"
from tt1 group by id;
ID 定位 调位 通告
---------- ---------- ---------- ----------
1 44 44 44
2 44 0 44
3 44 22 0
两条语句都可以实现相同的功能,但显然第二条语句更好一些。最初没有想到Oracle能将group by 后的icount多个结果进行相加,后来用了一下发现可以。
感叹Oracle 的Sql 功能还是很完善的。