数据库中有如下表:
部门、问题类型、日期
A 1 7-25
D 2 7-25
C 1 7-25
D 4 7-25
B 3 7-26
D 2 7-26
A 1 7-26
. . .
. . .如何实现下面的查询结果:
部门、问题类型1、问题类型2、问题类型3、问题类型4
A 数量 数量 数量 数量
B 数量 数量 数量 数量
C 数量 数量 数量 数量
D 数量 数量 数量 数量我不知如何写sql语句,试了几次都不行! 求高手帮忙!!!
部门、问题类型、日期
A 1 7-25
D 2 7-25
C 1 7-25
D 4 7-25
B 3 7-26
D 2 7-26
A 1 7-26
. . .
. . .如何实现下面的查询结果:
部门、问题类型1、问题类型2、问题类型3、问题类型4
A 数量 数量 数量 数量
B 数量 数量 数量 数量
C 数量 数量 数量 数量
D 数量 数量 数量 数量我不知如何写sql语句,试了几次都不行! 求高手帮忙!!!
也可用decode
sum(decode(问题类型,2,l,null)) "问题类型 2",
sum(decode(问题类型,3,1,null)) "问题类型 3",
sum(decode(问题类型,4,1,null)) "问题类型 4"
from 表名 group by 部门;
SQL> create table lc (id int,val int,valuetype int);表已创建。
SQL> insert into lc values (1,1,1);已创建 1 行。SQL> insert into lc values (1,2,1);已创建 1 行。SQL> insert into lc values (1,3,1);已创建 1 行。SQL> insert into lc values (1,4,2);已创建 1 行。SQL> insert into lc values (1,5,2);已创建 1 行。SQL> insert into lc values (1,6,2);已创建 1 行。SQL> insert into lc values (1,6,3);已创建 1 行。SQL> insert into lc values (2,6,1);已创建 1 行。SQL> commit;提交完成。SQL> select * from lc; ID VAL VALUETYPE
---------- ---------- ----------
1 1 1
1 2 1
1 3 1
1 4 2
1 5 2
1 6 2
1 6 3
2 6 1已选择8行。SQL> select id,sum(decode(valuetype,1,val,null)) "type 1",
2 sum(decode(valuetype,2,val,null)) "type 2",
3 sum(decode(valuetype,3,val,null)) "type 3"
4 from lc group by id; ID type 1 type 2 type 3
---------- ---------- ---------- ----------
1 6 15 6
2 6SQL>
---------- ----------
a 1
d 2
c 1
d 4
b 3
d 2
a 1已选择7行。SQL> select a.bm,(select count(*) from test1 b where b.bm=a.bm and b.lx=1) lx1,
2 (select count(*) from test1 b where b.bm=a.bm and b.lx=2) lx2,
3 (select count(*) from test1 b where b.bm=a.bm and b.lx=3) lx3,
4 (select count(*) from test1 b where b.bm=a.bm and b.lx=4) lx4
5 from test1 a group by bm;BM LX1 LX2 LX3 LX4
---------- ---------- ---------- ---------- ----------
a 2 0 0 0
b 0 0 1 0
c 1 0 0 0
d 0 2 0 1SQL>
使用waterfirer(水清)的方法需要连接的操作,运行时间会长到不可接受;对于daydayupliq(敞开胸怀!) 的decode()方法,不是太明白里面null的作用,高手们可不可以说明一下?
对所有的记录作以上运算和判断,然后将结果sum起来;
所以最后的得到的就是问题类型是1的记录数。用decode的好处是多个decode同时使用可以减小扫描table的次数:
用waterfirer(水清)的连接方法需要扫描五次table;
而用daydayupliq(敞开胸怀!) 的decode()方法只需要扫描一次table。
如果测试条件复杂一点的话,比如说case when(x.mon > 0 and x.mon<10) then x.cnt else 0 end
这个语句用decode要怎么写?
1.case expr
when value1 then ret1
when value2 then ret2
else ret3
end
2.case when expr1 then ret1
when expr2 then ret2
else ret3
end
decode相当于第一种方法,只能用于值相等的比较,对于case when(x.mon > 0 and x.mon<10) then x.cnt else 0 end属于第2种用法,decode实现要用到嵌套decode语句
sum(y.型1) as 问题类型1,sum(型2) as 问题类型2,
sum(型3) as 问题类型3,sum(型4) as 问题类型4
from
(
select x.部门,
decode(x.问题类型,'1',x.num ) as 型1,decode(x.问题类型,'2',x.num ) as 型2,
decode(x.问题类型,'3',x.num ) as 型3,decode(x.问题类型,'4',x.num ) as 型4
from (selecta.部门,a.问题类型 ,count(*) num
from 表 a
group by a.部门,a.问题类型
) x
) ygroup by y.部门