Oracle sql - join和group by子句用于提取大多数订单的顶级客户

时间:2016-11-10 20:50:39

标签: sql oracle

edit2:这就是我得到的:

表:http://imgur.com/a/Ecb5T

我正在努力拉出25%属于公司并拥有最多订单的客户。

我在下面尝试了查询:

Select customer_id,
(
Select Count(order_id) from order 
where commercial_customer.customer_id = order.customer_id
) AS Orders limit by 25/100 * (Count(*) from order) ;

但我正在

  

ORA-00923:找不到FROM关键字   00923.&00;"在预期的地方找不到FROM关键字"   *原因:
  *动作:行错误:5列:13

按照评论中的建议后,我得到了这个查询: http://imgur.com/a/9JPyN

它显示一切正确,但两者的订单均为3,因为Count(*)计算customer_id = 2的所有订单。

为了完成这项工作,我会使用

Select customer_id,customer_name,company_code,Orders
from xyz_customer,xyz_commercial, (
Select Count(*) AS Orders from xyz_order
**where customer_id=xyz_comcustomer.customerid**
)
where
rownum<=(select count(*)from XYZ_COMCUSTOMER)/3

但我得到了这个:

ORA-00904: "XYZ_COMCUSTOMER"."CUSTOMERID": invalid identifier
00904. 00000 -  "%s: invalid identifier"
*Cause:    
*Action:
Error at Line: 4 Column: 19

预期结果:
Customer_ID,Customer_name,Company_code,订单
4马林87654321 3
1 Alexa 12345678 1

3 个答案:

答案 0 :(得分:1)

尝试这样的事情(使用分析功能)

select *
 from
 (
   select customer_id, rank() over (order by count_orders) rank_orders
   from
   (
     select customer_id, count(*) count_orders
     from order
     group by cusomer_id
   )
 )
 where rank_orders <= round((select count(*) from order) / 4)

答案 1 :(得分:1)

select customer_id, cnt
  from (
    select customer_id, cnt, ntile(4) over(order by cnt desc) GRP
      from (
        select O.customer_id, count(*) cnt
          from xyz_order O, xyz_commercial_customer CC
         where O.customer_id=CC.customer_id
         group by O.customer_id
      )
  )
 where GRP=1

窗口函数ntile(4)将客户分为4组。第1组 - 按订单降序排列的1/4(25%)客户。

或者,仅使用嵌套查询(不推荐):

select *
  from (
        select O.customer_id, count(*) cnt
          from xyz_order O, xyz_commercial_customer CC
         where O.customer_id=CC.customer_id
         group by O.customer_id
         order by cnt desc
       )
 where rownum<=(select count(*) from xyz_commercial_customer)/4

答案 2 :(得分:0)

您可以使用customer_id和子选择

的count(*)组
select a.customer_id, a.customer_name
from customer a
inner join order b on a.customer_id = b.customer_id
group by a.customer_id, a.customer_name
having count(*) > (select count(*) from order )/4;