如果客户有资格购买多种产品,如何根据 SQL 中的下一个最佳报价模型对客户进行排名

问题描述 投票:0回答:1

我有一组有资格购买某种类型产品的客户:

客户 产品
约翰 香蕉
约翰 苹果
约翰 橙色
卡拉 香蕉
卡拉 苹果
卡拉 橙色

我还有一个模型,可以根据客户的喜好告诉我哪些产品最适合客户:

客户 最适合的产品 第二最适合的产品 第三最适合的产品
约翰 桃子 橙色 香蕉
卡拉 苹果 香蕉 桃子

如您所见,可能还有其他最适合的产品,但目前不符合条件。

我正在开展一项活动,但每个客户只能宣传两种产品。这是通过对外销售团队完成的,该团队要求我在数据集上有重复项。

我如何根据最适合的产品对它们进行排名,以便每个客户只有两行?

我想要这个:

客户 产品 排名
约翰 橙色 1
约翰 香蕉 2
卡拉 苹果 1
卡拉 香蕉 2

我还没有尝试过任何东西。

sql sql-server window-functions ranking
1个回答
0
投票

你可以这样做:

SELECT  customers.Customer, p.Product
, ROW_NUMBER() OVER(PARTITION BY customers.Customer ORDER BY p.sort) AS rank
FROM    (
    VALUES  (N'John', N'Banana')
    ,   (N'John', N'Apple')
    ,   (N'John', N'Orange')
    ,   (N'Carla', N'Banana')
    ,   (N'Carla', N'Apple')
    ,   (N'Carla', N'Orange')
) customers (Customer,Product)
INNER JOIN (
        VALUES  (N'John', N'Peach', N'Orange', N'Banana')
        ,   (N'Carla', N'Apple', N'Banana', N'Peach')
    ) products (Customer,[Most Suited Product],[Second Most Suited Product],[Third Most Suited Product])
    ON  products.Customer = customers.Customer
CROSS APPLY (
    VALUES ([Most Suited Product], 1),([Second Most Suited Product],2),([Third Most Suited Product],3)
    ) p (product, sort)
WHERE   p.product = customers.Product
  1. 您可以通过客户 ID 加入您的客户和产品表。
  2. 然后根据产品的适用性来调整产品。
  3. 最后,通过旋转的产品连接回来。然后排名就变成了一个简单的 ROW_NUMBER
© www.soinside.com 2019 - 2024. All rights reserved.