oracle 具有计数子查询

6ie5vjzr  于 2022-11-03  发布在  Oracle
关注(0)|答案(2)|浏览(213)

我试图得到一些查询,但我有一个问题,我有计数,它说我错过了一个表达式。请帮助

select d.kode, rpad(d.nama,75,' ') as "NAMA", lpad(count(th.fk_distributor),10,' ') as "JUMLAH"
    from mh_distributor d 
    join th_beli th on th.fk_distributor = d.kode
    having count(td.fk_produk) > select avg("JUMLAH") as "AVERAGE" from(
        select d.nama,count(th.fk_distributor) as "JUMLAH"
        from mh_distributor d
        join th_beli th on th.fk_distributor = d.kode
        group by d.nama
    )
    group by d.nama, td.fk_produk, d.kode
    order by d.kode asc;

这是我的疑问

vm0i2vca

vm0i2vca1#

只需将第二个select语句用子查询 Package 起来:

select avg("JUMLAH") 
from(select d.nama,count(th.fk_distributor) as "JUMLAH"
     from mh_distributor d join 
          th_beli th on th.fk_distributor = d.kode
     group by d.nama
    ) t;

所以,你的完整陈述应该是:

select d.kode, rpad(d.nama,75,' ') as "NAMA", 
      lpad(count(th.fk_distributor),10,' ') as "JUMLAH"
from mh_distributor d join 
     th_beli th 
     on th.fk_distributor = d.kode
having count(td.fk_produk) > (select avg("JUMLAH") 
                              from(select d.nama,count(th.fk_distributor) as "JUMLAH"
                                   from mh_distributor d join 
                                        th_beli th on th.fk_distributor = d.kode
                                   group by d.nama
                                 ) t
                             )
group by d.nama, td.fk_produk, d.kode
order by d.kode asc;
klsxnrf1

klsxnrf12#

使用窗口函数!

select nk.*
from (select d.kode, d.nama, count(*) as jumlah,
             avg(count(*)) over (partition by d.nama) as avg_jumlah
      from mh_distributor d join
           th_beli th
           on th.fk_distributor = d.kode
      group by d.nama, td.fk_produk, d.kode
     ) nk
where jumlah > avg_jumlah;

我省略了到字符串的转换,因为我认为这只会使逻辑更难遵循--当然,针对您的特定用例,将其添加回外部查询中。
这应该比复杂的having子句有更好的性能。

相关问题