我有一张表记录了不同类型的人员的进出,数据如下:
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呢?
谢谢!

解决方案 »

  1.   

    select type,sum(flag)
    from test
    group by type不行吗?
      

  2.   

    select  type,sum(flag) from test group by type order by type
      

  3.   

    select type,sum(flag) from test group by type;
      

  4.   

    我这个数据创建得不好,假如数据如下:
    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
      

  5.   

    大家看看四楼我的例子吧。可能我举例不对,大家可以这样想:
    a、b、c三个人分别去图书馆借c、c1、c2三种书,flag为1表示赠送,-1表示借,最后我想统计c、c1、c2这三种书数量发生变化的分别与多少人有关。
      

  6.   

    征对我4楼的例子,你们的语句得到的结果如下:
    SQL> select type,sum(flag)
      2  from test
      3  group by type
      4  /TYPE  SUM(FLAG)
    ---- ----------
    c            -1
    c1            3
    c2           -2
    显然不是我要的结果
      

  7.   


    a中一个是克隆人!(最近又看了遍 warStarwar
      

  8.   

    楼主的意图可以这样表示吧
    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 
    数据量大的时候,这个估算就差不多了。如果小的话,性能不会成为问题