我有一张表记录了不同类型的人员的进出,数据如下:
SQL> select * from test order by type;CODE FLAG TYPE
---- ---- ----
b -1 c
b 1 c1
a 1 c1
d -1 c2
c -1 c2
a 1 c2
a -1 c2
我想按照人员类型来汇总统计不同类型的最终人员数据(进入-出去),结果应该如下:
SQL> select type,sum(count) from (select count(distinct code)*flag count,type from test group by flag,type) group by type;TYPE SUM(COUNT)
---- ----------
c -1
c1 2
c2 -2
但是这个sql语句一个group by套用了另外一个group by,效率不高,请问能否有一个效率比较高的sql呢?
谢谢!
SQL> select * from test order by type;CODE FLAG TYPE
---- ---- ----
b -1 c
b 1 c1
a 1 c1
d -1 c2
c -1 c2
a 1 c2
a -1 c2
我想按照人员类型来汇总统计不同类型的最终人员数据(进入-出去),结果应该如下:
SQL> select type,sum(count) from (select count(distinct code)*flag count,type from test group by flag,type) group by type;TYPE SUM(COUNT)
---- ----------
c -1
c1 2
c2 -2
但是这个sql语句一个group by套用了另外一个group by,效率不高,请问能否有一个效率比较高的sql呢?
谢谢!
解决方案 »
- 统计每个学生的优良差,这语句该怎么写?
- PL SQL developer中如何批量执行sql脚本文件和procedure?
- 怎么判断数据库中某几个字段是否符合条件。查询结果是:是否有符合条件的值?
- 求教:oracle用truncate table 时报错
- 奇怪的SQL语句问题!紧急求助!
- oracle中varchar最大支持多少个汉字?
- 救救我吧 紧急求助: ORA-12560: TNS: 协议适配器错误
- 几个基础的问题!
- 后台存储过程运行和前台脚本运行数据同步问题求教,谢谢
- 请教高手:如何根据第二个表的相关字段内容更新第一个表的字段内容?
- oracle10G的dmp文件包如何导入到9i中
- DOS和文档可以互相选择编写?
from test
group by type不行吗?
SQL> select * from test order by type;CODE FLAG TYPE
---- ---- ----
b -1 c
a 1 c1
b 1 c1
a 1 c1
d -1 c2
c -1 c2
a 1 c2
a -1 c2
我要得到的结果是:
SQL> select type,sum(count) from (select count(distinct code)*flag count,type from test group by flag,type) group by type;TYPE SUM(COUNT)
---- ----------
c -1
c1 2
c2 -2
a、b、c三个人分别去图书馆借c、c1、c2三种书,flag为1表示赠送,-1表示借,最后我想统计c、c1、c2这三种书数量发生变化的分别与多少人有关。
SQL> select type,sum(flag)
2 from test
3 group by type
4 /TYPE SUM(FLAG)
---- ----------
c -1
c1 3
c2 -2
显然不是我要的结果
a中一个是克隆人!(最近又看了遍 warStarwar
select type,sum(sign(s))
from(
select sum(flag)s,code,type from test group by code,type)
group by type同样还是要group by 2次,性能不会有大改观
我觉得逻辑上来说,一个人在一段时间内进出房间,只有3种可能,进比出多1;进和出一样多;进比出少1。
除非数据有问题,如果偏差不大的话
select type,sum(flag)
from test
group by type
数据量大的时候,这个估算就差不多了。如果小的话,性能不会成为问题