oracle中count的最大值

时间:2014-09-15 21:39:19

标签: sql oracle

我有这些表,订单表:

Name       Null?    Type  
ORDER_ID  NOT NULL  NUMBER(5)  
CUSTOMER_ID         NUMBER(8)  
SHIPMENT_METHOD_ID  NUMBER(2)  

和Shipment_method表:

Name               Null?      Type  
SHIPMENT_METHOD_ID  NOT NULL  NUMBER(2)  
SHIPMENT_DESCRIPTION          VARCHAR2(80)  

我正在尝试根据订单获得最常用的送货方式,我是初学者,所以我需要一些帮助。 我在想是否有可能有MAX(count(order_id)),但我怎么能为每个shipment_method_id做到这一点?

4 个答案:

答案 0 :(得分:2)

你不需要MAX,你只需要返回第一行

SELECT Shipment_Method_Desc
FROM (
    SELECT Shipment_Method_ID, Shipment_Method_Desc, COUNT(*) AS ct
    FROM Shipment_Method s
    JOIN Orders o ON s.Shipment_Method_ID = o.Shipment_Method_ID
    GROUP BY Shipment_Method_ID
    ORDER BY ct DESC)
WHERE ROWNUM = 1

如果您使用的是Oracle 12c或更新版本,则可以使用row limiting clause代替子查询:

SELECT Shipment_Method_ID, Shipment_Method_Desc, COUNT(*) AS ct
FROM Shipment_Method s
JOIN Orders o ON s.Shipment_Method_ID = o.Shipment_Method_ID
GROUP BY Shipment_Method_ID
ORDER BY ct DESC
FETCH FIRST 1 ROW ONLY

答案 1 :(得分:2)

这是另一种方法:

select shipment_method_id, shipment_description, count(*) as num_orders
  from orders
  join shipment_method
 using (shipment_method_id)
 group by shipment_method_id, shipment_description
having count(*) = (select max(count(order_id))
                     from orders
                    group by shipment_method_id)

答案 2 :(得分:1)

这是一种方法,允许多个货件方法具有相同的最大订单数。

SELECT shipment_method_id
      ,shipment_description
      ,orders
FROM
   (SELECT shipment_method_id
          ,shipment_description
          ,orders
          ,rank() OVER (ORDER BY orders DESC) orders_rank
    FROM
       (SELECT smm.shipment_method_id
              ,smm.shipment_description
              ,count(*) orders
        FROM orders odr
             INNER JOIN shipment_method smm
               ON (smm.shipment_method_id = odr.shipment_method_id)
        GROUP BY smm.shipment_method_id
                ,smm.shipment_description
       )
   )
WHERE orders_rank = 1

答案 3 :(得分:0)

作为初学者,您可能会发现使用with非常有用,可以获得一些命名的中间结果:

with STATS as (select SHIPMENT_METHOD_ID, count(*) as N 
               from ORDERS group by SHIPMENT_METHOD_ID)
, MAXIMUM as (select max(N) as N from STATS)
select SHIPMENT_METHOD_ID, SHIPMENT_DESCRIPTION 
from STATS
join MAXIMUM on STATS.N = MAXIMUM.N
natural join SHIPMENT_METHOD