获取每组的前 10 行

Get the first 10 rows for each group

我有三个table:

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

因此 Order table 存储客户订购产品的次数。

我需要这样的视图:

TopOrder(Name, Product, nbCommands)

但是我只想给每个客户10个产品,他订购最多的那些我搞不懂。

dense_rank window 函数应该正是医生开的:

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