获取每组的前10行

时间:2015-06-04 07:23:58

标签: sql oracle select oracle11g top-n

我有三张桌子:

Customer(IdCustomer, Name)
Product(IdProduct, Product)
Order(IdProduct, IdCustomer, nbOrders)

因此订单表存储了客户订购产品的次数。

我需要这样的观点:

TopOrder(Name, Product, nbCommands)

但我只想为每位顾客提供10种产品,他订购的产品最多,我无法弄明白。

1 个答案:

答案 0 :(得分:3)

dense_rank窗口功能应该是医生规定的:

CREATE View TopOrder AS
SELECT Name, Product, nbOrders
FROM   (SELECT Name, Product, nbOrders,
               DENSE_RANK() OVER (PARTITION BY o.idCustomer
                                  ORDER BY nbOrders DESC) AS rk
        FROM   Customer c
        JOIN   Orders o ON c.idCustomer = o.idCustomer
        JOIN   Product p ON p.idProduct = o.idProduct
       ) t
WHERE  rk <= 10