如何使用特定规则选择最多3列中的前3个值?

2eafrhcq  于 2021-06-15  发布在  Mysql
关注(0)|答案(1)|浏览(300)

因此,我想找出前三名卖家(金额)在每个销售月为每个客户。
原始表格:

create table q2(Sales_Date date, Customer_ID varchar(256), Item varchar(256), Amount float);        

INSERT INTO q2              
VALUES              
    ('2018/8/1' ,'AAA'  , 'Apple'   , 5600),
     ('2018/8/8'    ,'AAA'  , 'Nike'    , 500),
     ('2018/8/9'    ,'AAA'  , 'Pear'    , 600),
     ('2018/8/10'   ,'AAA'  , 'Kindle', 900),
     ('2018/8/1'    ,'BBB'  , 'Cola', 20),
     ('2018/9/12'   ,'BBB'  , 'LEGO' , 240),
     ('2018/9/13'   ,'CCC'  , 'Apple' , 2500),
     ('2018/9/14'   ,'CCC'  , 'Kindle' , 5000),
     ('2018/7/4'    ,'CCC'  , 'Nike' , 1000),
     ('2018/9/7'    ,'CCC'  , 'Pear' , 300),
     ('2018/9/7'    ,'CCC'  , 'LEGO' , 50);

期望输出

我试过不同的方法,但都不管用。我怎样才能做到这一点?
到目前为止,我只能检索到最畅销的代码,但这是不够的。

SELECT
    m.Sales_month,
    m.Customer_ID,
    m.Item
FROM(
      SELECT
        Month(Sales_Date) as Sales_month,  
        Customer_ID, 
        Amount,
        Item,
        DENSE_RANK() OVER (PARTITION BY Month(Sales_Date), Customer_ID ORDER BY Amount Desc) AS 'rank'
        FROM q2  
    ) as m
WHERE m.rank = 1;

非常感谢!!

kmbjn2e3

kmbjn2e31#

我知道您希望每个客户和每个月的前三大销售额都在列中。
每个客户和每个月的排名记录是一个好的开始。然后,我们可以对每组前三条记录进行筛选,并使用条件聚合进行透视:

select sales_month, customer_id, 
    max(case when rn = 1 then item end) as item_1,
    max(case when rn = 2 then item end) as item_2,
    max(case when rn = 3 then item end) as item_3
from (
    select q.*,
        date_format(sales_date, '%Y-%m-01') as sales_month,  
        row_number() over (partition by customer_id, date_format(sales_date, '%Y-%m-01') order by amount desc) as rn
    from q2  
) q
where rn <= 3
group by sales_month, customer_id

请注意,这包括分组中的销售年度,而不是仅使用月份的原始代码。如果您的数据分布在一年以上,这是很方便的。

相关问题