表:SYS_USER  字段 USERID,USERNAME
                     001    张三
                     002    李四
                     003    王五表:HOS_CUST  字段 CUST_ID,CUST_NAME,DEV_ID1,DEV_ID2,DEV_ID3,DEV_ID4,DEV_ID5,CUST_TYPE
                    0001      A        张三           李四                      甲
                    0002      B        李四                    王五             乙
                    0003      C        张三           李四             王五     丙
                    0004      D        王五           李四                      丁
                    0005      E        王五           李四                      甲
                    0006      F        张三           李四                      丁
                    0007      G        张三                                     甲需要结果:USERID USERNAME    甲     乙      丙     丁
            001    张三       2      0       1      1
            002    李四       2      1       1      2
            003    王五       1      1       1      1表SYS_USER和表HOS_CUST有很多条记录,但甲乙丙丁是固定的只有四个,HOS_CUST中每条记录上同一个人最多只出现一次。5个位置至少有一个有名字。我自己写了条语句逻辑上没问题 就是查询起来非常慢。我第2个表中有上10万条记录。
哪位帮我写个效率点的语句,不胜感激!

解决方案 »

  1.   

    没看懂,数据有点乱但统计甲,乙,丙,丁,可以用sum(decode(甲,1,0)) 甲,sum(decode(乙,1,0)) 乙   .....
    这种方式 
      

  2.   

    select a.username, sum(decode(cust_type, '甲', 1)) 甲,
           sum(decode(cust_type, '乙', 1)) 乙,
           sum(decode(cust_type, '丙', 1)) 丙,
           sum(decode(cust_type, '丁', 1)) 丁
      from (select dev_id1 username, cust_type
               from host_cust
             union all
             select dev_id2 username, cust_type
               from host_cust
             union all
             select dev_id3 username, cust_type
               from host_cust
             union all
             select dev_id4 username, cust_type
               from host_cust
             union all
             select dev_id5 username, cust_type from host_cust) a, SYS_USER b
     where a.username = b.username
     group by a.username;
    这个由于你的设计的原因导致这个查询不会太快。你应该将dev_id1 ~ 5 直接拆成多行,那样建上索引就会快多了。
      

  3.   

    不过,10万行对oracle来说不是很大。我模拟了一下,
    userid USERNAME  甲      乙       丙       丁
    001 张三 21027 20844 20640 20933
    002 李四 20650 20882 20787 20652
    003 王五 20779 20780 20874 20983
    004 赵六 20733 20916 20817 21087
    005 陈七 20877 20988 20702 20694全查出来花费4.312秒。我的数据库是在我本机的虚拟机里装的,Oracle 9204,红帽linux 虚拟机内存512M。
      

  4.   

    有两种方法:
    1. 先汇总记录,再统计 group by
    2. 先统计group by ,再汇总 group by,汇总后的数据再合并sum