我有三张桌子:
Customer(IdCustomer, Name)
Product(IdProduct, Product)
Order(IdProduct, IdCustomer, nbOrders)
因此订单表存储了客户订购产品的次数。
我需要这样的观点:
TopOrder(Name, Product, nbCommands)
但我只想为每位顾客提供10种产品,他订购的产品最多,我无法弄明白。
答案 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