在sale_new_result表中需要获取province,city,dealercode(销售店号) ,companyname,province province2,companycity,count(dealercode) total (销售店总数)这些字段,但在 group by后只需按city,dealercode分组就可以了,但为了同时能查询出其它字段我也只好把其它不需要分组的字段也加到 group by后去,这样虽然不影响结果(在我这个例子中),但总觉这种方法不太好,求其它的解决方法,请大家指点指点,先谢了!
查询代码如下:
select  province,city,dealercode ,companyname,province province2,companycity,count(dealercode) total  from sale_new_result a
  where  countdate>=200906 and countdate<=200909 
and 
   dealercode in(SELECT distinct dealercode FROM SALE_NEW_MASTER where province=substr(a.province,0,length(a.province)-1))
and substr(city,0,length(city)-1) not in (SELECT distinct city FROM SALE_NEW_MASTER where province=substr(a.province,0,length(a.province)-1))group by  province, city,companyname,dealercode,companycity

解决方案 »

  1.   

    select  min(province),city,dealercode,min(companyname),min(province) province2,min(companycity),count(dealercode) total  from sale_new_result a 
      where  
    group by  city,dealercode
      

  2.   

    用max() over(parition by order by ....)
      

  3.   

    group by  province, city,companyname,dealercode,companycity
    和group by  city,dealercode
    结果是一样的?按city,dealercode分组时同一个分组内的其他字段值都相同的话
    可以用max(province),max(companyname)...
    不影响结果另外,in后面的子查询中distinct没有必要
    这样试试
    select  max(province),city,dealercode ,max(companyname),max(province) province2,max(companycity),count(dealercode) total  from sale_new_result a 
      where  countdate>=200906 and countdate <=200909 
    and 
       exists(SELECT 1 FROM SALE_NEW_MASTER where a.province like province||'_' and dealercode=a.dealercode) 
    and   not exists (SELECT 1 FROM SALE_NEW_MASTER where a.province like province||'_' and a.city like city||'_') group by  city,dealercode
      

  4.   

    select city,dealercode ,min(province),min(companyname),min(province ),min(province2),min(companycity),count(dealercode) total 
     group by city,dealercode 
      

  5.   

    select distinct province,city,dealercode ,companyname,province province2,companycity,count(*) over(partition by city,dealercode) total 
    from sale_new_result a 
      where  countdate>=200906 and countdate <=200909 意思就这样了,基本COPY你的代码,只是换了一个分析函数,错误你自己找找,运气好直接通过
      

  6.   

    如果需要根据聚合值条件查询非聚合记录,建议使用窗口分析函数获得聚合值,而其它字段使用常规输出,然后通过派生表(select 常规输出字段 from ( 含窗口分析函数的嵌套查询 )where 聚合值条件  ),在数据量不是非常大的结果集中,用它可以避免对表的多次扫描,减少IO,窗口分析函数在单次表扫描期间分配window(sort)工作区实现,在内存足够完成单步排序的情形下,通过充分利用CPU运算能力,而实现性能提升.尤其在需要多个不同聚合粒度聚合值为条件进行的判断中,效果更为显著.